Model the validation tokens that can be added in a class:
1. Required Fields
[Required]
public string FirstName {get; set;}
2. field Length
Up to n bits:
[Stringlength (160)]
public string FirstName {get; set;}
Requires at least n bits:
[Stringlength (Minimumlength=3)]
public string FirstName {get; set;}
3. Regular Validation
[RegularExpression (@ "[A-za-z0-9._%+-][email protected][a-za-z0-9.-]+\.[ a-za-z]{2,4} ")]
public string Email {get; set;}
4. Scope
[Range (35,44)]
public int Age {get; set;}
The case of decimals:
[Range (typeof (Decimal), "0.00", "49.99")]
Public decimal price {get; set;}
5. Validation of service-side participation
[Remote ("Checkusername", "account")]
public string UserName {get; set;}
Then specify a Checkusername method in the AccountController:
Public Jsonresult Checkusername (string username) { var result = Membership.findusersbyname (username). Count = = 0; return Json (result, jsonrequestbehavior.allowget);}
6. Compare
[RegularExpression (@ "[A-za-z0-9._%+-][email protected][a-za-z0-9.-]+\.[ a-za-z]{2,4} ")]
public string Email {get; set;}
[Compare ("Email")]
public string Emailconfirm {get; set;}
7. custom Error Messages
Regular:
[RegularExpression (@ "[A-za-z0-9._%+-][email protected][a-za-z0-9.-]+\.[ a-za-z]{2,4} ",
errormessage= "Email doesn ' t look like a valid email address.")
public string Email {get; set;}
Normal text:
[Required (errormessage= "Your Last name was Required")]
[Stringlength (errormessage=, Your Last name was too long ")]
public string LastName {get; set;}
PLACEHOLDER:
[Required (errormessage= "Your {0} is Required.")]
[Stringlength (errormessage= "{0} is too long.")]
public string LastName {get; set;}
third, backstage action the wording
There are two things to do in action: to determine if a modelstate is legitimate, and to add an error message. The login action that comes with the MVC3 template is as follows:
[Httppost]public actionresult LogOn (Logonmodel model, string returnUrl) { if (modelstate.isvalid) { if ( Membership.ValidateUser (model. UserName, model. Password)) { Formsauthentication.setauthcookie (model. UserName, model. RememberMe); if (Url.islocalurl (RETURNURL) && returnurl.length > 1 && returnurl.startswith ("/") &&! Returnurl.startswith ("//") &&!returnurl.startswith ("/\\")) { return Redirect (RETURNURL); } else { return redirecttoaction ("Index", "Home"); } } else { modelstate.addmodelerror ("", "the user name or password provided is incorrect."); } } If we got this far, something failed, redisplay form return View (model);
Original address: http://www.cnblogs.com/yeagen/archive/2012/09/24/2700836.html
MVC Model Validation