Go: MVC Data validation

Source: Internet
Author: User

first, the basic characteristics

  first, Required

Required option, A validation error is raised when the submitted form is missing this Value.

  second, Stringlength

Specify the allowed length

Specify the maximum Length:

[stringlength ()] // maximum length of 20 characters or less

Specify the shortest limit to the maximum:

[stringlength (minimumlength=3)] // maximum length of 20 characters or less, minimum of 3 characters

  third, RegularExpression

The regular expression can match the string, if it does not match, then report a validation error

[regularexpression (@ "[a-za-z0-9.%+-][email protected][a-za-z0-9.-]+\.[ a-za-z]{2,4}")]

such as mailbox format verification:

[regularexpression (@ "^\[email protected][a-za-z_]+?\.[ a-za-z]{2,3}$"" Please enter the correct e-mail address! ")]

  four, Range

The range attribute is used to specify the minimum and maximum values for numeric type Values.

[Range (+)]    //  Integral type, min. 35, max. [Range (typeof(decimal),"0.00","49.99" )]    //Decimal Type

  five, Remote

Allows client-side validation logic to be performed using the Server's callback Function. To be blunt is to support Ajax Validation.

    A reference namespace is Required: System.Web.Mvc;

This is a demo that writes the existence of an asynchronous authentication user Name:

        [Required]        [Remote ("checkusername""Home")  )]        publicstring  UserName        {            get;             Set ;        }

Controller code:

         public Jsonresult checkusername (string  UserName)        {            booltrue;             if " Admin " )            {                false;            }             return Json (result,jsonrequestbehavior.allowget);        }

Show Results:

    

Notice that the value of username is sent by Ajax to the Server-side Judgment.

liu, Compare

Used to ensure that two objects of a template object have the same Value.

For example, It is time for the Compare property to be required to confirm the password again after the password is usually entered.

[Compare (" property name to compare ] ")

    

  The above features require using System.ComponentModel.DataAnnotations;

Also be aware that the two options in Web. Config are set to true;

    <add key="clientvalidationenabled" value="true"/>    <add key="unobtrusivejavascriptenabled" value="true "/>
II. Custom Error message

Each attribute allows the passing of a parameter with a custom error prompt Message.

        [Required (errormessage=" username must be filled in ")]        [Remote ("checkusername" "Home", errormessage= " This user name already exists " )]        publicstring  UserName        {            get;             Set ;        }

  

Custom error messages, There is also a format item, such as

[Required (errormessage="{0} must be filled "string  name{  get ;   Set ;    }

{0} is replaced with the name when it is Entered.

If the above verification method is not enough, you can also customize the validation, and then forget that you can turn to the "asp. MVC3 Advanced programming" page 127th. Here is not to write the demo, use to write Again.

Iii. Displaying and editing annotations

  1. Display

If you are using a direct Editorformodel implementation, the display feature can help you set a friendly show name

For example:

[Display (name=" password ")]  public string Get set; }

The results appear as follows:

  

The display also supports the order in which attributes are displayed, such as

[Display (name=" password "15000)]  public string Get Set ; } [Display (Name=" password "15001)]  public string Get set; }

The next order is to show the order of the edit boxes, which by default is 10000, sorted by Revaluation.

2, Scaffoldcolumn

Hiding HTML helper methods (such as Editorformodel,displayformodel) displays some Properties.

[scaffoldcolumn (false)]        // edit box for this property is not displayed  public string Get set; }

Although Scaffoldcolumn can not display some properties on the page to be edited, but if the submitted form has this property value, the model binding mechanism will still bind this property Value. To remove the explicit [Bind], this is not related to this article. Not mentioned Here.

3, DisplayFormat

The DisplayFormat attribute can be used to handle various formatting options for a Property. When a property contains a null value, you can provide optional display text, or you can turn off HTML encoding for the property that contains the tag, and you can specify a format string for the runtime to apply to the property Value.

For example:

true " {0:c} " )]publicdecimalgetset; }

thus, when there is an initial value, the code shown will look like this:

  

Note that is the initial value, if it is directly filled out, there will be no SIGN. Look at the initial values set in the Controller:

         public ActionResult Personadd ()        {            New  person_model ();             12.10M ;             return View (p);        }

This display style is not useful for submitting back to the controller, because the model binder will not be able to resolve the returned price Value. How to use your own discretion, to show or Ok.

  4, ReadOnly

If you ensure that the default model binder does not update the properties with the new values in the request, you can add the ReadOnly attribute to the Attribute:

[ReadOnly (true)]  public string Get set; }

Note that this property still displays an editable text box to display name, but the model binder does not receive its value, so only the model binder considers the ReadOnly Property.

  5, DataType

The datatype attribute can provide the runtime with information about the specific purpose of the Property.

For example:

[DataType (datatype.password)]  public string Get set; }

The display results are as follows:

  

This property can be used to specify multi-select buttons, radio buttons, password entry boxes, and so on for the type of Data.

  6, UIHint

The UIHint feature provides a template name to the asp. net MVC runtime, in case the template helper methods such as (displayfor and Editorfor) render output are Used. You can also customize your own template helper methods to override the default behavior of asp.

  7, Hiddeninput

Hiddentinput in namespace System.Web.Mvc, it tells the runtime to render an INPUT element with a type attribute value of "hidden". Plainly is <input type= "hidden" value= "xxx"/>

Iv. Validation Examples

Start by creating a new MVC Project. Add the following code, the code is very simple: a Person_model class

     public class Person_model    {        [Required]        publicintgetset;}        [Required]          public string Get Set ; }        [Required]          public int Get Set ; }    }

Controller class Code:

     public classHomecontroller:controller { publicActionResult personadd () {returnView (); } [httppost] publicActionResult personadd (person_model Model) {//a line of code to determine whether validation passes            if(modelstate.isvalid) {returnRedirect ("/home/personmanager"); }            returnView (); }    }

View Code:

@model Mvcapplication1.models.person_model@{viewbag.title="Index"; Layout="~/views/shared/_layout.cshtml";}<form action="/home/personadd"Method="Post">Id:<input type="text"Name="Id"Value=""/>@Html. validationmessagefor (Model= Model.id)//The reason that the Person_model is written in the validation will show the tip of the front, mainly the role of this Code<br/>name:<input type="text"Name="Name"Value=""/>@Html. validationmessagefor (Model=Model.name)<br/>age:<input type="text"Name=" age"Value=""/>@Html. validationmessagefor (Model=Model.age)<input type="Submit"Value="Determine"/></form>

First look at the effect of execution:

This example is verified, Note that there is no client authentication, is fully server-side validation, if there is an error, the view will render again, very useful ah, very convenient ah, how many lines of code you have to write in the past to solve these tedious and tasteless verification? Microsoft is too sympathetic to programmers, the top one.

In the previous example, when the data sent to the server verification does not pass, then all users fill out the page after the reopening of the empty, if you want to not empty, that is, the first time the user filled out the content is still there, you can return to the View (the object received);

V. Enabling Client-side Validation

Other than that. It seems that the front-end does not perform validation a bit of a waste of server resources, if we want the front-end to verify the first pass and then commit, this can reduce the number of server-side verification, not every time there are some small problems to the Server-side verification and then return it! So how do you enable Client-side validation? Powerful microsoft, again worshipping, to enable front-end Verification. You just need two steps.

The first step: the following 4 files are Introduced.

<link href="@Url. Content ("~/content/site.css")"Rel="stylesheet"Type="Text/css"/> <script src="Http://www.cnblogs.com/Scripts/jquery-1.7.2.min.js"Type="Text/javascript"></script> <script src="Http://www.cnblogs.com/Scripts/jquery.validate.min.js"Type="Text/javascript"></script> <script src="Http://www.cnblogs.com/Scripts/jquery.validate.unobtrusive.min.js"Type="Text/javascript"></script>

Step two: Add the form header:

@{    html.enableclientvalidation ();}

ok, This is very good, not because some trivial to submit the form to the Server. The form to the server is submitted only when the client has passed the validation, and the server is validated when a form is Submitted.

Vi. changing the error tip style

For the wrong hint style, in/content/site.css, you can find the style you want to use, change it, and in the validation error, The view will have a inline style, including the validated HTML control and the error prompt.

  Special Note: If you want the front-end display to take effect, that is, do not send data to the server, the front-end to verify and display error message, then the introduction of the form must use mvc, such as:

@using (html.beginform ()) {    }

If you write your own <form></from> front-end hints are not valid.

Go: MVC Data validation

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.