ASP MVC5----Common data annotations and validation

Source: Internet
Author: User

Just keep walking and slow down.

When using the MVC pattern for development, data annotations are often used (on top of the model), and here are some common uses of my reading.

What is validation, data annotations

Verify

From a global perspective, Discovery logic is only a small part of the entire validation. Verify that you first need to manage user-friendly (localized) error messages related to validation logic, and when validation fails, present the error message to the user interface and, of course, provide the user with a mechanism to recover from the validation failure.

Data annotations

Annotations are a common mechanism that can be used to inject metadata into the framework, while the framework not only drives metadata validation, but also uses metadata when generating HTML markup for displaying and editing models. Popular is the specific identifier above the model (with some meaning and effect).

verifying the use of annotations

The definition of data annotations in the generic namespace "System.ComponentModel.DataAnnotations" provides server-side validation, and when used on model properties, the framework also supports client authentication. You can add an error prompt after the annotation, and errormessage is the parameter used in each validation attribute to set the error message, such as:

        [Required (errormessage = "cannot be Empty")]        public int Age {get; set;}
    • Required

The emphasis attribute is mandatory and cannot be empty. A validation error is raised when one of the properties is null or empty.

        [Required]        public int Age {get; set;}
    • Stringlength

Requires the length of the name to be entered. Parameters can be limited to a minimum. As follows:

        [Stringlength (160,minimumlength = 3)]        public string Name {get; set;}
    • RegularExpression

Regular expression validation, such as where a mailbox needs to be verified. is very convenient, thus reducing the service side of the validation.

        [RegularExpression (@ "^ ([a-za-z0-9_-]) [email protected] ([a-za-z0-9_-]) + (. [ A-za-z0-9_-]) + ", errormessage =" Mailbox input is incorrect, re-enter. ")] public                string Email {get; Set }
    • Range

Used to specify the value type worth the minimum and maximum values. mainly for int type service. The rest is also possible, requiring the use of overloaded versions of constructors. The type parameter to do.

       [Range (20,30,errormessage = "Age does not meet the requirements")]        public int Age {get; set;}
        [Range (typeof (Decimal), "0.00", "59.99")]        Public decimal price {get; set;}
    • Compare

Determines that two model properties have the same value. Password verification (enter two times to see if they are the same.) ), the parameter is the value of the preceding model.

        [Required (errormessage = "Password cannot be empty")]        public string Password {get; set;}        [Compare ("Password")]        public string Passwordpalt {get; set;}
    • Remote

This attribute executes the client's validation logic using a server-side callback function. In layman's words, this feature can directly find the action of a controller and execute the method.

        <summary>        ///Verify that the name entered in the model is duplicated in the database///</summary>//        <returns></returns> Public        Jsonresult Checkusername (string username)        {
            Related validation in the database            return Json (DateTime.Now.ToString (), jsonrequestbehavior.allowget);        }
        [Remote ("Checkusername", "Admin")]        public string UserName {get; set;}

The above controller action validates with a parameter with the same name as the Username property and returns a Boolean type value (0/1) in a JavaScript object Notaion (JSON).

    • Custom Reply message Placeholder

Use the {0} placeholder to display the user's input and to form a friendly hint.

        [Range (20,30,errormessage = "Age {0} does not meet the requirements")]        public int Age {get; set;}
some processing on the server side (authentication and binding)

The validation features of ASP. NET MVC are composed of model binders, model metadata, model validators, and model states.

Validation and model binding

    • Adding parameters to the action method

There is an implicit implementation of the model binding, which we generally need to write, so it is safe to say that the parameters are not exposed.

    • Perform bindings explicitly using the Updatemodel or TryUpdateModel method

This actual project is rarely used, and is typically converted implicitly.

        [Httppost,actionname ("Create")]        Public ActionResult Createpost (Student model)        {            var model2 = new Student ();            Updatemodel (MODEL2);            if (TryUpdateModel (MODEL2))            {                             }            return View (model);        }

you can see the implicit conversion in the arguments, and the model2 inside is an explicit conversion. The bool type is returned in the IF. Once the model binder has updated the model properties with the new values, it takes advantage of the current model metadata to get all the validators for the model. The MVC runtime provides a validator (dataannotationsmodelvalidator) to work with the data annotations, which will find all the validation attributes and execute the validation logic they contain. The model binder captures all failed validation rules and puts them into the model state .

An important principle of programming is the inability to trust user input

Validation and model state

The by-product of model binding is the model state, which is the modelstate of our server-side validation, which contains not only the user's input, but also all errors of each related property (errors related to the state of the model itself), errors, and Modelstate.isvalid returns false. So that we can verify it.

        Public ActionResult Createpost (Student model)        {            var s=modelstate.isvalidfield ("UserName");             var ss=modelstate["UserName"]. Errors.Count;            var userName = modelstate["UserName"]. Errors[0]. errormessage;  Get error message            if (modelstate.isvalid)      //return bool type            {                             }            return View (model);        }
Displaying and editing annotations
    • Display

Display Model properties Set friendly "display name"

        [Display (name = "name")]        [Stringlength (160,minimumlength = 3)]        public string Name {get; set;}
    • Scaffoldcolumn

Helper methods that can hide HTML

        [Scaffoldcolumn (false)]        public string Address {get; set;}
    • DisplayFormat

Processing properties Various formatting options, when the property contains a null value, can provide optional display text. You can also turn off HTML encoding for attributes that contain tags. You can also specify a format string to apply to the property value at run time.

        [DisplayFormat (Applyformatineditmode = true,dataformatstring = "{0:c}")]        Public decimal Total {get; set;}
    • ReadOnly

You can ensure that the default model binder does not use the new values in the request to update the properties.

    • DataType

The runtime provides information about the specific purpose of the property. Properties of type string can be applied to many occasions--e-mail addresses, URLs or passwords can be saved.

        [Required (errormessage = "Password cannot be empty")]        [DataType (Datatype.password)]        public string Password {get; set;}
    • UIHint

Provide the runtime with a template name for use when invoking the template helper method to render the output.

Custom validation Logic
    1. Encapsulates the validation logic in a custom data annotation.
    2. Encapsulates the validation logic in the model object.

Encapsulating the validation logic in custom data annotations makes it easy to reuse logic in multiple models. You need to write code inside attributes to handle different types of models.

Custom annotations

All validation annotation attributes are ultimately derived from the base class Validationattribute, which is an abstract class that is defined in System.ComponentMode.DataAnnotation. The same custom validation logic must derive from the Validationattribute class. and rewrite the IsValid method (the method implements our corresponding logic).

Requirement: Limit the number of words the user enters in the address and set a maximum value.

    <summary>////Custom model validation///input number of words maximum////</summary> public class Maxwordsattribute:valida        Tionattribute {private readonly int _maxword;        Public maxwordsattribute (int maxword) {_maxword = Maxword;            } protected override Validationresult IsValid (object Value,validationcontext validationcontext) { if (value!=null) {//Converts the input to string type var valueasstring = value.                ToString (); Use the split (') space to separate the input values and count the number of generated strings.                Compare the number to verify. if (Valueasstring.split (").  Length>_maxword) {return new Validationresult ("Word exceeds length");         String Type}} return validationresult.success; BOOL Type}}

The first parameter validates the value in the object. The logic behind the judgment. Do not display the error prompt here to the foreground. We need to modify the error message by using the ErrorMessage property of Validationattrubute to customize the prompt.

After modification

public class Maxwordsattribute:validationattribute {private readonly int _maxword; Public Maxwordsattribute (Int. Maxword): Base ("{0} has too many words") {_maxword = Maxwo        Rd            } protected override Validationresult IsValid (object Value,validationcontext validationcontext) { if (value!=null) {//Converts the input to string type var valueasstring = value.                ToString (); Use the split (') space to separate the input values and count the number of generated strings.                                Compare the number to verify. if (Valueasstring.split ("). Length>_maxword) {var errormessage = Formaterrormessage (Validationcontext.displaynam                     e);                  return new Validationresult (errormessage);         }} return validationresult.success; BOOL Type}}
        [Maxwords (5)]                public string Address {get; set;}

This will show the error message in our base class.

We can add custom error displays based on the model.

        [Maxwords (5,errormessage = "The number of words you entered is over-bounds, please retype it.) ")] public                string Address {get; Set }

Here we need to pay attention to the order of execution, which is to perform the validation above the model, and then go to the action in the controller. Use the Modelstate.isvalid to verify.

Self-validating model (Ivalidatableobject)

The self-validating model refers to a model object that knows how to validate itself, allowing the class to implement the Ivaalidatableobject interface to authenticate itself.

    public class Information:ivalidatableobject    {public        ienumerable<validationresult> Validate ( Validationcontext validationcontext)        {            if (Username!=null&&username.split ("). length>5)            {                 yield return new Validationresult ("Word over Bounds");}                     }        [Display (name = "user name")]        public string UserName {get; set;}            }

In fact, the book above is a string type of array returned in the error return value, as follows

Yield return new Validationresult ("Word over bounds", new []{"UserName"});

I don't know where to get this error message. Can only be displayed separately. In fact, put the error message in the array can be multi-model validation, so that the unified error display.

Own feelings if you need to validate the model, it is best to do the first method, at least the code looks clean, the second kind of feeling is very messy, but the second is suitable for comparison model more occasions.

I am me, the color is not the same fireworks.

ASP MVC5----Common data annotations and 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.