0

This current project I am trying to get a registration form and pass it through validation. I am pretty new to C# and ASP.NET MVC4. I am trying to prevent a user being added to a collection of the incoming Post data is invalid. Here is my controller code, followed by my User class with rules using System.ComponentModel.DataAnnotations

If the data is invalid then I want to throw a custom error (i have not begun implementing this just yet).

Controller:

[HttpPost]
        public ActionResult Confirm(FormCollection form)
        {
            string firstName = form["textFirstName"];
            string lastName = form["textLastName"];
            string email1 = form["textEmail"];
            string password1 = form["passwordPW1"];

            User newUser = new User { fName = firstName, lName = lastName, email = email1, password = password1 };

            if (ModelState.IsValid)
            {
                _users.Add(newUser);
            }
            return RedirectToAction("Login", "Countdown");
        }

Model:

public class User
    {
        [Required]
        [StringLength(50, MinimumLength = 1)]
        public String fName { get; set; }

        [StringLength(50)]
        public String lName { get; set; }

        [Required]
        [RegularExpression(@"^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$")]
        public String email { get; set; }

        [Required]
        [StringLength(50, MinimumLength = 4)]
        public String password { get; set; }
    }
5
  • What is the problem? Commented Nov 4, 2014 at 8:24
  • When i pass it invalid input it will still add the user to the collection. Commented Nov 4, 2014 at 8:26
  • 1
    You seem to be manually doing what the model binder will do automatically. Change your method signature to Confirm(User data) and make sure the field names in HTML match the property names (which you can do with @Html.TextBoxFor() etc). Then your validation attributes will work. Commented Nov 4, 2014 at 8:26
  • Jon go for Model Binding, Model binding will take care of the validations. Commented Nov 4, 2014 at 8:44
  • Have a look here asp.net/mvc/overview/getting-started/introduction/… Commented Nov 4, 2014 at 8:49

1 Answer 1

4

There is no validation without model binding, and since you are not doing any model binding, ModelState will never be invalid.

You need to bind the model somehow, either by changing your method parameter to take your model type, or by calling UpdateModel or TryUpdateModel.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.