(12) ASP. NET MVC Data validation

Source: Internet
Author: User

ASP. NET MVC automatically checks based on the type of the attribute, such as an int type attribute, which will report an error when committing a non-integer type of data. In Action can be judged according to Modelstate.isvalid whether the validation passed, if not passed, use the following method to obtain the error message:

 Public Static stringgetvalidmsg (modelstatedictionary modelstate) {StringBuilder sb=NewStringBuilder (); //iterate through all the properties        foreach(varKeyinchModelstate.keys) {//if the current property validation passes, the next property is directly            if(Modelstate[key]. Errors.Count <=0)            {                Continue; } sb. Append ($"property "{Key}" error:"); //Traverse all error validation information for the current property            foreach(varErrorinchModelstate[key]. Errors) {sb. Appendline (Error.            ErrorMessage); }        }        returnsb. ToString ();}

Note: For modelstatedictionary modelstate, use the class under SYSTEM.WEB.MVC namespace.

ASP. NET MVC provides the ability to validate the request data on the server side, as long as the Attribute is marked on the corresponding model attribute.

Common validation Attribute:

    • [Required]: Required
    • [Stringlength (100)]: string Maximum length 100
    • [Stringlength (mininumlength=10)]: string length between 10 and 100
    • [RegularExpression ("Regular expression")]: match with regular expressions
    • [Range (35,80)]: Values range from 35 to 88
    • [Compare ("Password")]: Label This attribute property as the value of the Password property
    • [EmailAddress]: to conform to the mailbox format

Verify that there are errormessage properties on the Attribute that can be used to customize the error message, and {0} can be used as the placeholder for the property name in ErrorMessage.

For some validation rules, we can customize them. such as verifying QQ number:

// Validationattribute under the System.ComponentModel.DataAnnotations namespace  Public class qqnumberattribute:validationattribute{    public Qqnumberattribute ():base (@ "  ^d{5,10}$")    {        this'{0} property is not a valid QQ number ";    }}

You can also override the IsValid () method:

 Public classqqnumberattribute:validationattribute{ PublicQqnumberattribute () { This. ErrorMessage ="{0} property is not a valid QQ number"; }
Public Override BOOLIsValid (Objectvalue) { BOOLFlag = Regex.IsMatch (value. ToString (),@"^d{5,10}$"); returnFlag; }}

(12) ASP. NET MVC Data validation

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.