MVC 3 Data validation Model Validation detailed

Source: Internet
Author: User

Continue with the knowledge point we mentioned earlier for the next point of knowledge analysis, this time we will explain the data validation. In fact, this is a very easy to understand and grasp the place, but this will waste everyone a lot of time, so I have to summarize and tidy up, saving everyone valuable time.

In the MVC 3 data validation, has been applied very common, we need in the Web Form ERA in the view side through JS to verify each need to verify the value of the control, and the availability of such validation is very low. But in the new era of MVC, we can validate our data with the data validation attribute provided by MVC. and MVC provides client and server-side double-layer authentication, only we disable the client JS, will also perform service-side validation, so greatly improve our development progress. Today we are together as a beginner to enter the hall of data validation.

First, in order for MVC data validation to take effect on the client, we must import the necessary JS libraries. In one of my blogs, I specifically described how chained validation is done through Jquery.validate.js.

 1 <script src= "@Url. Content (" ~/scripts/jquery-1.5.1.min.js ")" Type= "Text/javascript" ></script>2 & Lt;script src= "@Url. Content (" ~/scripts/jquery.validate.min.js ")" Type= "Text/javascript" ></script>3 < Script src= "@Url. Content (" ~/scripts/jquery.validate.unobtrusive.min.js ")" Type= "Text/javascript" ></script 
then we need to add the corresponding model, in fact, the model layer in MVC is not necessarily an entity class, it can also be a domain model. The difference is still there. Let's add a simple user class,
1 namespace Mvcapplication4.models 2 {3 public class UserInfo 4 {5//id No. 6 [Scaffoldcolumn (Fals e)] 7 [Required (allowemptystrings = false, ErrorMessage = "User ID cannot be empty")] 8 [Display (Name = "record number", Order = 2 0000)] 9 public int ID {get; set;}         [Display (Order = 15000)]12 [Required (allowemptystrings = false, errormessage = "User name cannot be empty")]13 [Stringlength (minimumlength = 6, errormessage = "User name cannot be greater than {2} and is less than {1}")]14 [Remote ("User", "Validate", Httpmeth OD = "Post", errormessage = "User name already exists")]15 public string UserName {get; set;} [Display (name= "password")]19 [DataType (Datatype.password)]20 [Required (AllowEmpty Strings = False, errormessage = "Password cannot be empty")]21 [Stringlength (minimumlength = $, errormessage = "Password must be between {2} and {1} ")]22 public string UserPassword {get; Set        }23 [Required (allowemptystrings = false, ErrorMessage = "Mailbox Required")]25 [RegularExpression (@ "[a-za-z0-9._%+-][email protected][a-za-z0-9]+\.[ a-za-z]{2,4} ", errormessage =" {0} is malformed ")]26 public string Email {get; set;}  [Compare ("email", errormessage = "Mailbox to be the same")]29 public string Temail {get; set;} Compare if the case is the same, it will not trigger validation. [Display (Name = "ID number")]33 [RegularExpression (@ "\d{17}[\d|x]|\d{15}", ErrorMessage = "Identity card number format error")]34 public string Identityno {get; set;} [Required (allowemptystrings = false, ErrorMessage = "Age Required")]37 [Range (+, errormessage = "Age cannot be large {2} cannot be less than {1} ")]38 public int: Age {get; set;}         [ReadOnly (True)]41 [DisplayFormat (Applyformatineditmode = true, DataFormatString = "{0:c}")]42          [Required (errormessage = "Amount cannot be empty")]43 [Range (typeof (decimal), "20.0", "30.0", errormessage = "Amount between {1} and {2}")]44 Public decimal Money {get; set;} 45}46}

In the model layer UserInfo class, we define the attributes that a user should have and the different validations that need to be added for each attribute. With the model set up, we need to display the corresponding view layer through the controller.

In fact, the controller does not need to do any processing, only need to select a suitable view for the page display. The most important thing is in the view layer.

 @{2 Layout = null, 3} 4 @model MvcApplication4.Models.UserInfo 5 <!     DOCTYPE html> 6 

I've defined two ways to display the model data in the view layer, one through HTML. Editorfor (model) shows each of the different properties separately, and another neat way is through HTML. Editorformodel (), this method will provide error message display and so on.

Model, view, controller are set up, let's look at the results of the final run.

In, we see two identical parts, which is the effect I display with two different display modes. There are two of them, both of which pass through as soon as one is validated. The root cause is that their ID values are the same.

Seeing the actual effect, let's analyze one by one the method of implementation of each validation attribute is very important.

Required required indicates that the field value is required.

[Required (allowemptystrings = false, errormessage = "User name cannot be empty")]

The Display field displays a name that indicates that the field displays the name value instead of the field itself.

[Display (name= "password")]

Stringlength represents the length of the validation string. We can set the minimum length and maximum length, if not within this range, you will be prompted with an error message

[Stringlength (minimumlength = 6, errormessage = "User name cannot be greater than {2} and is less than {1}")]

Where we see a placeholder exists in the errormessage, in fact, this placeholder is easy to understand that {0} represents the name of the field itself, {1} represents the first parameter before it, and {2} represents the second parameter before it.

Scaffoldcolumn represents whether the MVC framework is used to handle set to true for processing with the MVC framework, and if set to false, the field is not displayed on the view layer, and the validation defined in it does not take effect.

[Scaffoldcolumn (False)]

Remote indicates a remote authentication, which is equivalent to the Ajax method of requesting the server asynchronously and returning information. The most common is to verify that the user name is duplicated. The following validation is an asynchronous call to the user Action below Validatecontroller and returns the result as a JSON value.

  [Remote ("User", "Validate", HttpMethod = "POST", ErrorMessage = "username already exists")]

DataType represents the data type of the field, which affects the display of the field in the view layer. If set to password, the input is replaced with a *.

[DataType (Datatype.password)]

RegularExpression Regular expression validation. Regular expressions I have been introduced in one of my blog posts. Regular expressions are a powerful tool for validating strings that we must master. The preceding is the validation mode, followed by an error message displayed in error.

Use regular expressions to crawl the blog list data

[RegularExpression (@ "[A-za-z0-9._%+-][email protected][a-za-z0-9]+\.[ a-za-z]{2,4} ", errormessage =" {0} is not in the correct format ")]

Compare compare two field values is the same, this if we use JS to verify, a minimum of three rows, which is only a client-side validation. Then it's easier to implement in MVC.

[Compare ("email", errormessage = "Mailbox to be the same")]

There is one place to note in compare validation, which is the first parameter, which is the name of another field, we must note that the case is correct, and if wrong, the validation will not pass.

Range represents the size of the size of data validation. This attribute can verify the size range of values for data types such as Int,double,decimal. Represents between 10 and 100, including 10 and 100

[Range (errormessage = "age cannot be greater than {2} cannot be less than {1}")]

ReadOnly Indicates whether the field is read-only. This in the view layer I sometimes test will not be executed. The exact reason is unknown.

DisplayFormat represents the style of the data display. In fact, this does not belong to the data validation feature, but should belong to the data format. If you want to enable formatting, the first parameter must be set to true, and the second one is the same as the parameter following the ToString () method.

[DisplayFormat (Applyformatineditmode = true, DataFormatString = "{0:c}")]

UiHint tells MVC the specified template.

Hiddeninput hidden Field Display

In fact, I personally is the data validation of these features are divided into two categories, one is the real validation, Required,range,stringlength,display,remote,regularexpression,compare,range. These features are attribute that are really validated. Several other display,readonly,datatype,displayformat,scaffoldcolumn are related to the display of fields, and there is no real and server-side validation.

We can use the various validation features provided by MVC, so can we define custom attribute validation ourselves. MVC has a huge scalability, and we can extend it ourselves, in two ways, one that can be reused and validated in the MVC framework, as long as it inherits from Validationattribute and can be reused as a validation feature, and the other is a schema that is contained within. It is only a validation of a specific model, inherited from Ivalidatableobject can implement the validation of word inclusions.

Reusable validation attributes, inherited from Validationattribute.

1 Public   class Maxwordsattribute:validationattribute 2     {3  4         maxwordsattribute (int maxwords) 5             : Base ("{0} string too long") 6         {7             _maxwords = maxwords; 8         } 9         private readonly int _maxwords;10         protected override Validationresult I Svalid (object value, Validationcontext validationcontext),         {             if (value! = null)                 valueasstring = value. ToString ();                 valueasstring.split ("). Length > _maxwords) ~                 {                     var errormessage = formaterrormessage (                     validationcontext.displayname) ;                     return to New Validationresult (errormessage),                 }22             }23             return validationresult.success;24         }25     }

The MVC validation feature improves the efficiency and stability of our development and deserves our learning. Or that sentence, every day to learn, oneself often progress, the world is better.

MVC's validation extension features and globalization, we have the opportunity to learn together in the future.

MVC 3 Data validation Model Validation detailed

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.