简体   繁体   中英

ASP.NET MVC4 server side validation

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; }
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM