. NET MVC Model Validation Summary

Source: Internet
Author: User
Tags valid email address

The model in ASP. MVC4 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 MVC4 framework do the validation for us. I use the login with the MVC4 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 MVC4 '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 of which is ValidationSummary, it 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, add the verification mark in the model

The MVC4 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:

Validation tokens that can be added in the Model 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._%+-]+@[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._%+-]+@[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;}

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, the writing of the background action

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 MVC4 template is as follows:
[HttpPost] Public ActionResult LogOn (Logonmodel model, string returnUrl) {if (modelstate.isvalid) {if (membership.valid Ateuser (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]This action can only be called by the 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 given to the @Html. ValidationSummary display.

Alternatively, you can refer to your own style to make the cue box more aesthetically pleasing.

< Link rel = "stylesheet" type= "Text/css" href= "/content/css/site.css"/>


. NET MVC 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.