Data validation for ASP. MVC3 (i)

Source: Internet
Author: User

Original: Data validation for ASP. MVC3 (i)

For web developers, validating the information entered by the user is an important but tedious task, and many developers will ignore it.    The ASP. NET MVC3 Framework uses a method called "Data Annotations" (dataannotations) for data validation. This approach allows the program to perform two-step verification on both the client and server side (the ASP. NET data validation control is also double-validated).    The benefit of two-factor authentication is that client authentication directly corresponds to the user, without submitting the form, easing the pressure on the server and improving the user experience, while server-side validation ensures the validity and completeness of the data, because sometimes the client shuts down the scripting functionality. Note: To implement client-side validation, you need to reference jquery and jquery validation files:

<script src= "@Url. Content (" ~/scripts/jquery-1.5.1.min.js ")" Type= "Text/javascript" ></script>< Script src= "@Url. Content (" ~/scripts/jquery.validate.min.js ")" Type= "Text/javascript" ></script>< Script src= "@Url. Conten (" ~/scripts/jquery.validate.unobtrusive.min.js ")" Type= "Text/javascript" ></script >
to implement server-side validation, you need to execute the Modelstate.isvalid after submitting the form first, the basic verification 1, Require (non-null verification)Model:
[Required]        [Display (name = "user name")]        public string UserName {get; set;}
Validation results:

2. Stringlength (string length verification)The maximum length and minimum length of the model property can be verified, respectively, corresponding to theMaximumLengthAndminimumlength, where minimumlength is optional. Model:
        [Required]        [Stringlength (minimumlength = 6)]        [DataType (Datatype.password)]        [Display (Name = "password")]        public string Password {get; set;}
Validation results

3, RegularExpression (regular expression)Validates the property that conforms to the regular expression. Model:
        [Required]        [DataType (datatype.emailaddress)]        [RegularExpression (@ "[A-za-z0-9._%+-][email protected][a-za-z0-9._]+\.[ a-za-z]{2,4} ")]        [Display (Name =" e-mail Address ")] public        string Email {get; set;}
Validation results:

4. Range (value range verification)Used to specify the maximum and minimum values for a numeric value, the first parameter is the minimum value, and the second parameter is the maximum value (including themselves). can be user int type and double type. Model:
        [Required]        [Range (+)]        [Display (name= "age")]        public int Age {get; set;}
Validation results:

Second, additional verificationAdditional validation is an additional two validation feature in SYSTEM.WEB.MVC, so you must add a using SYSTEM.WEB.MVC when you use it 1. Remote AuthenticationAlthough ASP. NET MVC3 provides many features that validate data directly in the model, many logical and complex validations are not validated in model, so the MVC3 framework provides this Remote authentication feature that allows developers to use C # in Controller        Code to verify the validity of the data. A very classic app when verifying that the user name is duplicated. This data verifies that there is no way to authenticate to the client unless all user names are sent to the client (obviously this is not possible). So the remote feature is only server-side verified. But it is validated in an asynchronous way, so there is a better user experience. Model:
        [Required]        [Display (name = "user name")]        [Remote ("Checkusername", "Account")]        public string UserName {get; set;}
Controller:
        Public Jsonresult Checkusername (string userName)        {            var result = UserName = = "admin";            return Json (result, jsonrequestbehavior.allowget);        }
Validation Result: Note: If you want post submission, you need to add httpmethod= "POST":
[Required (Errormessageresourcetype=typeof (errormessage), errormessageresourcename= "Userrequire")]        [Display (name = "user name")]        [Remote ("Checkusername", "Account", httpmethod= "POST")]        public string UserName {get; set;}

The controller can also directly accept the POST request, of course, you add [HttpPost] is also possible:

        [HttpPost] public        jsonresult checkusername (string userName)        {            var result = userName! = "admin";            return Json (result, jsonrequestbehavior.allowget);        }
2, Compare (same authentication)The Compare attribute is used to verify that the two data entered are identical. The most typical example is whether the password entered twice at the time of registration is the same. Model:
        [Required]        [Stringlength (errormessage = "{0} must contain at least {2} characters. ", Minimumlength = 6)] [        DataType (Datatype.password)]        [Display (Name =" password ")] public        string Password {get; Set }          [DataType (Datatype.password)]        [Display (Name = "Confirm password")]        [Compare ("Password", errormessage = " The password and confirmation password do not match. ")] public        string ConfirmPassword {get; Set }
Validation results:

The above is a few common data annotations of the ASP. MVC3 Framework, in addition to the latter two MVC characteristics, the other features are in the System.ComponentModel.DataAnnotations, the appropriate use will greatly improve the development efficiency. specifically see: http://msdn.microsoft.com/zh-cn/library/system.componentmodel.dataannotations.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.