MVC verification (combination of model annotation and non-intrusive script), mvc Annotation

Source: Internet
Author: User

MVC verification (combination of model annotation and non-intrusive script), mvc Annotation

@ HtmlHrlper tags automatically generate some attributes, some of which are about verification.

Example:

 

 

Model Annotation

After model annotation, MVC verification, including front-end client, backend server verification, and MVC are all included, even if the user disables Javascript on the client, the server will also verify the illegal operations. The current premise is that the annotations are identified for the Model object.

 

The following steps (Prerequisites) are required for normal non-empty legitimacy verification ):

1. The Required feature must be added to each object type, but the numeric attribute is added by default.

2. The following script must be imported to the View:

<Script src = "~ /Scripts/jquery-1.7.1.js "> </script> <script src = "~ /Scripts/jquery. validate. js "> </script> <script src = "~ /Scripts/jquery. validate. unobtrusive. js "> </script> -- Non-embedded Scripts

3. The property configuration in the configuration file is as follows:

  <appSettings>    <add key="ClientValidationEnabled" value="true" />    <add key="UnobtrusiveJavaScriptEnabled" value="true" />  </appSettings>

Default built-in MVC style:

<link href="~/Content/Site.css" rel="stylesheet" />

Key namespaces:

using System.ComponentModel.DataAnnotations;using System.ComponentModel;using System.Web.Mvc;

 

Use instance

 

1. Non-empty Verification

Tag attributes:

[Required (ErrorMessage = "cannot be blank")] public string dUserName {get; set ;}

Add @ Html. ValidationMessageFor to the tag created in the view. This tag is prompted when a verification error occurs, essentially a span tag.

  @Html.TextBoxFor(d=>d.dUserName)  @Html.ValidationMessageFor(d=>d.dUserName)

 

 

 

Ii. restrict the length of text box input

Key code:

[StringLength (10, MinimumLength = 4, ErrorMessage = "the name length must be between 4 and 10")] public string dUserName {get; set ;}

 

 

 

3. Add a description to the control of the form item

Key code:

[DisplayName ("name")] public string dUserName {get; set ;}

Add the corresponding code to the view code:

@ Html. DisplayNameFor (d => d. dUserName)

Results:

 

 

 

4. Restrict the value range of integers and mark the attributes as follows:

[Range (100, 1000, ErrorMessage = "minimum: yuan, up to Yuan")]

 

 

5. Ensure that the input in the text box is the same as that in the other text box (the two passwords can be used for the same input)

[Compare ("Pwd1", ErrorMessage = "two different passwords")]

The first parameter is the name of the property to be matched.

 

 

6. Use Regular Expressions

[RegularExpression ("\ d +", ErrorMessage = "the password must be a pure number")]

 

 

7. Custom type form tags

Background code:

[DataType (DataType. EmailAddress)] [DisplayName ("Email")] public string Email {get; set ;}

 

 

Foreground use:

@ Html. displayNameFor (d => d. email) ---- prompt text @ Html. editorFor (d => d. email) ----- the custom type label is in the email format @ Html. validationMessageFor (d => d. email) --- error message tag prompt

 

 

Enter the error message here. The default message is English. You can change the file to Chinese:

 

 

8. Remote annotation attribute pairs, text box input, connect to the database through Ajax, and determine the validity (this method is used to connect to the database with ajax during validation)

For example, it can be used to check whether the user name has been used during registration. The magic effect is as follows:

 

Note: Remote Authentication is performed through Ajax requests. To prevent the cache from being written as a post request

Tagging:

[Remote ("checkUsername", "Donation", ErrorMessage = "username already exists", HttpMethod = "post")]

CheckUsername (action Method)

Donation (Controller name)

 

Examples of using the Action method:

[HttpPost] public ActionResult checkUsername () {// 1. obtain the check value string uname = Request ["dUserName"]; // 2. connect to the database and Judge DonationEntities db = new DonationEntities (); var model = db. donationDetail. firstOrDefault (d => d. dUserName = uname); if (model! = Null & model. dUserName = uname) {return Content ("false");} return Content ("true ");}

 

 

9. Background Verification

The MVC verification client depends on the js script file. If you disable JavaScript in your browser,

At this time, I can use the following countermeasures in the background.

 

// Verify that all attributes marked with feature labels in the object are valid. if one of them is invalid, false if (ModelState. isValid = false) {/* the corresponding prompt message in the returned view for verification failure * view requires @ Html. use the ValidateionSummry (true) label with */ModelState. addModelError ("", "entity Verification Failed"); return View ();}

 

 

 

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.