ASP. NET MVC Model validation (v)

Source: Internet
Author: User

ASP. NET MVC Model Validation ( Five ) Preface

The previous article mainly explains the Modelvalidatorprovider and modelvalidator two types of custom implementations, but in the MVC framework gives us other ways to do model validation, which is the subject of this article, The model validation using a series of feature types provided by the framework is also customizable, in the following demo example, I'll simulate the implementation by using our own custom attribute type (inherited from the Validationattribute type) into the custom model binder.

Model Validation
    • Model validation Simple Application Example
    • Modelvalidator using the build process
    • Custom Implementation Defaultmodelbinder to verify
    • Custom Modelvalidatorprovider and Modelvalidator
    • Validationattribute attribute classes use
    • Custom Validationattribute An example implementation of an attribute class

Validationattribute Attribute class use

Let's first look at the definition of the Validationattribute type, example code 1-1.

Code 1-1

     Public Abstract classValidationattribute:attribute {protectedValidationattribute (); protectedValidationattribute (func<string>errormessageaccessor); protectedValidationattribute (stringerrormessage); //Summary://Gets or sets an error message that is associated with a validation control in the case of a validation failure. //        //return Result://the error message associated with the validation control.          Public stringerrormessage {Get;Set; }  Public stringErrormessageresourcename {Get;Set; }  PublicType Errormessageresourcetype {Get;Set; } protected stringerrormessagestring {Get; }  Public Virtual stringFormaterrormessage (stringname);  PublicValidationresult Getvalidationresult (Objectvalue, Validationcontext validationcontext); //        //Summary://determines whether the specified value of the object is valid. //        //Parameters://Value://The value of the object to validate. //        //return Result://true if the specified value is valid; otherwise, false.          Public Virtual BOOLIsValid (Objectvalue); protected VirtualValidationresult IsValid (Objectvalue, Validationcontext validationcontext);  Public voidValidate (ObjectValuestringname);  Public voidValidate (Objectvalue, Validationcontext validationcontext); }

The Validationattribute type is the base class for all of the attribute types applied on the model property in the following example, in the Validationattribute type above, the ErrorMessage property represents the information displayed by the validation error, IsValid () method is to indicate whether the validated value is passed, let's take a look at a simple example of the model validation attribute class that the framework gives us.

First, we'll use the sample code in the ASP. NET MVC Model validation (a) to see the definition of ViewModel using the validation attribute class, example code 1-2.

Code 1-2

namespacemvcapplication.models{/// <summary>    ///viewmodel-User Registration Information/// </summary>     Public classregistrationinformation {[Required] Public stringID {Get;Set; } [Required] Public stringUserID {Get;Set; }        [Required] [Stringlength (Ten)]         Public stringPassword1 {Get;Set; } [Compare ("Password1")]         Public stringPassword2 {Get;Set; }  Public stringName {Get;Set; } }}

In code 1-2, we see some of the attribute classes applied to the Model property, and here's a brief description of what these types mean.

Required:[required], which indicates that this property must not be empty (including an empty string), or, of course, can be considered nullable by setting the internal Allowemptystrings property to True.

Stringlength:[stringlength (10)], the maximum length of a string that represents this property value cannot exceed 10.

Compare:[compare ("Password1")], indicating that the value of this property must be the same as the value of the specified property, the value of PASSWORD2 in the example must be the same as the value of the Password1 property, or a validation error message will be prompted

Let's take a look at the result diagram after the project is run.

Figure 1

Figure 1 deliberately entered these values, see 2 is the result of validation

Figure 2

Example implementations of custom Validationattribute attribute classes

In this section, we take a direct look at the custom model validation attribute type, which looks directly at the definition of example code 1-3.

Code 1-3

namespacemvcapplication.modelvalidators{[AttributeUsage (Attributetargets.property,allowmultiple=true, inherited=false)]     Public classCustommodelvalidatorattribute:validationattribute { Public Override BOOLIsValid (Objectvalue) {            if(string. IsNullOrEmpty ((string) value) | |string. Compare ((string) value,"Jinyuan",true) ==0) {errormessage="cannot be empty, or the name is not legal!"; return false; }            Else            {                return true; }        }    }}

Here's why to rewrite the base class's IsValid () method, perhaps the MVC framework calls this method to determine whether the current value passes validation, here's an aside, in the MVC framework I've looked through the default binder type implementation code, and did not find a call to the model validation attribute class. The great God knows the words to tell the younger brother grateful.

Now let's change the definition in code 1-2, example code 1-4.

Code 1-4

[Custommodelvalidator]  Public string Get set; }

After the modification, let's take a look at the results Figure 3 and Figure 4.

Figure 3

Figure 4

See here, a little forget, want to simulate the implementation of the default binder internal implementation, this part of the content is for reference only, example code 1-5.

Code 1-5

 Public classCustommodelvalidatorattributemodelbinder:defaultmodelbinder {protected Override voidSetProperty (ControllerContext controllercontext, Modelbindingcontext BindingContext, PropertyDescriptor PropertyDescriptor,Objectvalue) {            Base.            SetProperty (ControllerContext, BindingContext, PropertyDescriptor, value); foreach(Attribute attinchpropertydescriptor.attributes) {if(att ismodelvalidators.custommodelvalidatorattribute) {Modelvalidators.custommodelvalidat Orattribute MVA= att asModelvalidators.custommodelvalidatorattribute; if(!mva. IsValid (value)) {BindingContext.ModelState.AddModelError (Propertydescriptor.nam E, MVA.                    ErrorMessage); }                }            }        }    }

In code 1-5 we get to all the attribute classes applied on the model property based on the parameters of the PropertyDescriptor type, then filter to our custom type, make a validation judgment and then add its error message to Modelstate, We need to register our custom model binder with the system and run it as shown in Figure 3, as shown in Figure 4. The same can be achieved function, here just let everyone to the default binder to create a reverie space.

is the blog Park swollen recently? It's a little bit of a problem. Just sent the mail not much will be the problem and to solve it, really to force!!!

Jinyuan

Source: http://www.cnblogs.com/jin-yuan/

This article is copyrighted by the author and the blog Park, welcome reprint, but without the consent of the author must retain this statement, and on the article page

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.