MVC Model Validation Summary and common regular expressions

Source: Internet
Author: User
Tags valid email address

This article is reproduced, source:

Http://www.byywee.com/page/M0/S868/868615.html

About model validation official information:

Http://msdn.microsoft.com/zh-cn/library/system.componentmodel.dataannotations.aspx

The model in ASP. MVC3 is self-validating, which is through the process. The NET4 System.ComponentModel.DataAnnotations namespace is completed. All we have to do is give the model class each property plus the corresponding validation id memento (Attributes) to let the MVC3 framework help us complete the verification. I use the login with the MVC3 project template to illustrate the model validation.


First, enable client authentication:


The client verifies that the master completes the verification in order to improve the user experience by not brushing the Web page.


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 in the Verified view page to participate in such two JavaScript, attention, they are attached to 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 displays a summary of the validation messages, 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 To participate in the verification logo memento sign


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 the popular C # class, we invent each property with more than the square brackets "[]" flank the logo memento flag. In this case, [Required] is a validation of the identity memento flag, while [display], [DataType] is to display the corresponding HTML control, which is not within the scope of this comment debate.


In addition to required, we can also add other valid validation identification memento flags in the model. The following is a more complete list:


Model The memento flag that can be added to the class in the validation ID:




1. Required Fields
[Required]
public string FirstName {get; set;}
2. Field length
Up to n bits:
[Stringlength (160)]
public string FirstName {get; set;}
Request at least n bits:
[Stringlength (Minimumlength=3)]
public string FirstName {get; set;}

3. Regular validation

[RegularExpression (@ "[a-za-z0-9._%+-]+@[a-za-z0-9.-]+/. [A-za-z] {2,4} ")]
public string Email {get; set;}

4. Limitations
[Range (35,44)]
public int Age {get; set;}
The spectacle of decimals:
[Range (typeof (Decimal), "0.00", "49.99")]
Public decimal price {get; set;}

5. Validation of the side involvement

[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. Fighting strength
[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:
[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;}

Popular 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: Determine if Modelstate is legitimate, 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);
}

[HttpPost] This action can only be called through the process post action, which is for the form in the common view, because the action of the form is post (and of course, so get), but this is not within the limits of the comment debate in this article.


if (Modelstate.isvalid) is the focus, if not unexpected, that is, the client browser is not closed JavaScript, and the customer is not a hacker (hackers may be through the process of some object imitation post), as long as through the process of normal path The model of the post to this action should be isvalid. Of course, one of the first principles of programming is that you cannot rely on the input of the user, so we need to judge Modelstate.isvalid once more.


The Modelstate.addmodelerror method is to return an error message to the view, which is ultimately given to @html.validationsummary display.



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}¥"

0 and nonzero digits: "^ (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 the user's cipher: "^[a-za-z]/w{5,17}¥" the correct pattern is: The letter opening, length between 6~18, can only contain 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 de law number: ^ (/(/d{3,4}-) |/d{3.4}-)? /d{7,8}¥ "The correct pattern 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 pattern is:" 01 "~" 09 "and" 1 "~" 12 ".

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

MVC Model Validation Summary and common regular expressions

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.