Summary of ASP. NET mvc3 Model Verification

Source: Internet
Author: User
Tags valid email address

Http://www.wyjexplorer.cn/Post/2012/8/3/model-validation-in-aspnet-mvc3

The model in ASP. NET mvc3 is self-verified, which is completed through the. net4 system. componentmodel. dataannotations namespace. All we need to do is add the corresponding butes to the attributes of the model class so that the mvc3 framework can help us complete the verification. I will use the built-in logon IN THE mvc3 Project template as an example to explain the model verification.

1. Enable client Verification:

Client verification is mainly used to improve user experience and complete verification without refreshing the webpage.

The first step is to enable client verification in Web. config. This is already available in the template project that comes with mvc3:

<Add Key="Clientvalidationenabled" Value="True"/><Add Key="Unobtrusivejavascriptenabled" Value="True"/>

Then add the following two JavaScript codes to the verified view page. Note that they depend 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>

Two types of verification messages are displayed: validationsummary, which displays a Summary of the verification messages, including the messages returned from the background action.

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

The other is the verification message of the HTML control corresponding to each attribute in the model:

@ Html. validationmessagefor (M => M. username)

2. In ModelAdd verification mark

The built-in logon model class of the mvc3 Project template is as follows:

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 ;} }

Compared with the common C # class, we find that each attribute has a tag enclosed by square brackets. [Required] is a type of verification tag, while [display] and [datatype] are used to display the corresponding HTML control, which is not covered in this article.

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

ModelVerification tags that can be added to the class:

1.Required field

[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 (160, minimumlength = 3)]

Public String firstname {Get; set ;}

3.Regular Expression Verification

[Regularexpression (@ "[A-Za-z0-9. _ % +-] + @ [A-Za-z0-9.-] + \. [A-Za-Z] {2, 4}")]

Public String email {Get; set ;}

4.Range

[Range (35,44)]

Public int age {Get; set ;}

Decimal:

[Range (typeof (decimal), "0.00", "49.99")]

Public decimal price {Get; set ;}

5.Server-side Verification

[Remote ("checkusername", "account")]

Public String username {Get; set ;}

Then, specify a checkusername method in accountcontroller:

Public Jsonresult checkusername (String Username){VaR result = membership. findusersbyname (username). Count = 0;Return JSON (result, jsonrequestbehavior. allowget );}

 

6.Comparison

 

[Regularexpression (@ "[A-Za-z0-9. _ % +-] + @ [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 Expression:

[Regularexpression (@ "[A-Za-z0-9. _ % +-] + @ [A-Za-z0-9.-] + \. [A-Za-Z] {2, 4 }",

Errormessage = "email doesn't look like a valid email address.")]

Public String email {Get; set ;}

Common text:

[Required (errormessage = "your last name is required")]

[Stringlength (160, errormessage = "your last name is too long")]

Public String lastname {Get; set ;}

Placeholder:

[Required (errormessage = "your {0} is required.")]

[Stringlength (160, errormessage = "{0} is too long.")]

Public String lastname {Get; set ;}

Iii. Background actionStatement

There are two tasks to be done in Action: checking whether modelstate is valid and adding error messages. The built-in logon action of 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 ); }

[Httppost] indicates that this action can only be called through the Post action. This is used in combination with the form in the view, because the form action is post (or get ), however, this is beyond the scope of this article.

If (modelstate. isvalid) is important. If no accident occurs, that is, the client browser does not close JavaScript, and the customer is not a hacker (the hacker may simulate post using some tools ), as long as the model that post to this action through the normal channel should be isvalid. Of course, an important principle of programming is that we cannot trust user input, so we need to judge modelstate. isvalid again.

The modelstate. addmodelerror method returns an error message to the view and returns it to @ html. validationsummary.

Add a common Regular Expression (found online)

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

N-digit: "^ \ D {n} $ ".

At least n digits: "^ \ D {n ,}$ ".

M ~ N-digit :. "^ \ D {m, n} $"

Number starting with zero or zero: "^ (0 | [1-9] [0-9] *) $ ".

There are two decimal positive integers: "^ [0-9] + (. [0-9] {2 })? $ ".

1 ~ Positive number of three decimal places: "^ [0-9] + (. [0-9] {1, 3 })? $ ".

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

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

3 characters: "^. {3} $ ".

A string consisting of 26 English letters: "^ [A-Za-Z] + $ ".

String consisting of 26 uppercase letters: "^ [A-Z] + $ ".

A string consisting of 26 lower-case letters: "^ [A-Z] + $ ".

String consisting of digits and 26 English letters: "^ [A-Za-z0-9] + $ ".

String consisting of digits, 26 English letters, or underscores: "^ \ W + $ ".

Verify the User Password: "^ [A-Za-Z] \ W {5, 17} $". The correct format is: start with a letter, with a length of 6 ~ It can only contain characters, numbers, and underscores.

Check whether ^ % & ',; =? $ \ "And other 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 -./? % & =] *)? $ ".

Verification phone number: "^ (\ D {3, 4}-) | \ D {3.4 }-)? \ D {7,8} $ "correct format:" XXX-XXXXXXX "," XXXX-XXXXXXXX "," XXX-XXXXXXX "," XXX-XXXXXXXX "," xxxxxxx "and" XXXXXXXX ".

Verify the ID card number (15 or 18 digits): "^ \ D {15} | \ D {18} $ ".

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

31 days of verification for a month: "^ (0? [1-9]) | (1 | 2) [0-9]) | 30 | 31) $ "the correct format is;" 01 "~ "09" and "1 "~ "31 ".

Related Article

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.