ASP. NET MVC3 Model validation Summary

Source: Internet
Author: User
Tags valid email address

The model in ASP. MVC3 is self-validating, which is passed. The NET4 System.ComponentModel.DataAnnotations namespace is completed. All we have to do is add the corresponding validation tag (Attributes) to each property of the model class and let the MVC3 framework do the validation for us. I use the login with the MVC3 project template to illustrate the model validation.

First, enable client authentication:

Client-side validation is primarily intended to improve the user experience and to complete validation without the Web page being brushed back.

The first step is to enable client-side validation in Web. config, which is already available in MVC3 's own template project:

<add key= "clientvalidationenabled" value= "true"/><add key= "unobtrusivejavascriptenabled" value= "true"/ >

Then on the Verified view page to add two JavaScript, note that they are dependent on jquery:

<script src= "@Url. Content (" ~/scripts/jquery.validate.min.js ")" Type= "Text/javascript" ></script>< Script src= "@Url. Content (" ~/scripts/jquery.validate.unobtrusive.min.js ")" Type= "Text/javascript" ></script

There are two types of validation messages, one is ValidationSummary, which can display a summary of the validation message, including messages returned from the background action

@Html. ValidationSummary (True, "Login was unsuccessful. Please correct the errors and try again. ")

The other is the validation message for each property in the model that corresponds to the HTML control:

@Html. validationmessagefor (M = m.username)

second, in model add a validation tag to the

The MVC3 project template comes with the following login model classes:

public class logonmodel{    [Required]    [Display (Name = ' User name ')] public    string UserName {get; set;}     [Required]    [DataType (Datatype.password)]    [Display (Name = "Password")]    public string Password {get; set;}     [Display (Name = "Remember me?")]    public bool RememberMe {get; set;}}

In contrast to ordinary C # classes, we find that each attribute has more tags surrounded by square brackets "[]". where [Required] is one of the validation tags, [display], [DataType] is to display the corresponding HTML control, which is outside the scope of this article.

In addition to required, we can add other useful validation tags to the model. The following is a more complete list:

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 (ret            Urnurl);            } 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);} 

[HttpPost] means that this action can only be called by a post action, in order to match the form in view, because the action of the form is post (which can also be a get), but this is not within the scope of this article.

if (Modelstate.isvalid) is the focus, if not unexpected, that the client browser does not turn off JavaScript, and the customer is not a hacker (hackers may use some tools to simulate post), as long as the normal way The model of the post to this action should be isvalid. Of course, one of the important principles of programming is that you cannot trust the input of the user, so it is necessary to judge Modelstate.isvalid again.

The Modelstate.addmodelerror method is to return an error message to the view, which is eventually presented to @html.validationsummary.

Finally attached regular expressions (online search)

Number: "^[0-9]*$".

N-bit number: "^\d{n}$".

Number of at least n digits: "^\d{n,}$".

Number of m~n bits:. "^\d{m,n}$"

Numbers starting with 0 and non 0: "^ (0|[ 1-9][0-9]*) $ ".

Positive real number with two decimal places: "^[0-9]+ (. [ 0-9]{2})? $ ".

Positive real number with a decimal position: "^[0-9]+ (. [ 0-9]{1,3})? $ ".

Non-zero positive integer: "^\+?" [1-9] [0-9]*$].

A non-zero negative integer: "^\-[1-9][]0-9" *$.

A character of length 3: "^. {3}$ ".

A string consisting of 26 English letters: "^[a-za-z]+$".

A string consisting of 26 uppercase English letters: "^[a-z]+$".

A string consisting of 26 lowercase English letters: "^[a-z]+$".

A string consisting of a number and 26 English letters: "^[a-za-z0-9]+$".

A string consisting of numbers, 26 letters, or underscores: "^\w+$".

Verify user password: "^[a-za-z]\w{5,17}$" is in the correct format: start with a letter, length between 6~18, can contain only characters, numbers, and underscores.

Verify that it contains ^%& ',; =?$\ ' characters: "[^%& ',; =?$\x22]+".

Only Chinese characters can be entered: "^[\u4e00-\u9fa5]{0,}$"

Verify email Address: "^\w+ ([-+.] \w+) *@\w+ ([-.] \w+) *\.\w+ ([-.] \w+) *$ ".

Verify InternetURL: "^http://([\w-]+\.) +[\w-]+ (/[\w-./?%&=]*)? $ ".

Verify the phone number: "^ (\ (\d{3,4}-) |\d{3.4}-)? \d{7,8}$" The correct format is: "Xxx-xxxxxxx", "xxxx-xxxxxxxx", "xxx-xxxxxxx", "xxx-xxxxxxxx", " XXXXXXX "and" XXXXXXXX ".

Verify the Social Security number (15-bit or 18-digit number): "^\d{15}|\d{18}$".

Validation 12 months of the year: "^ (0?[ 1-9]|1[0-2]) $ "The correct format is:" 01 "~" 09 "and" 1 "~" 12 ".

Verify one months of 31 days: "^ ((0?[ 1-9]) | ((1|2) [0-9]) |30|31) $ "correct format for;" 01 "~" 09 "and" 1 "~" 31 ".

ASP. NET MVC3 Model validation Summary

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.