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