asp.net MVC model verification based on callout feature: Validationattribute

Source: Internet
Author: User

We know from the previous introduction that Modelvalidatorproviders's static read-only providers maintains a global Modelvalidatorprovider list, The modelvalidator that are ultimately used for model validation are provided through these modelvalidatorprovider. For the three kinds of modelvalidatorprovider that the list defaults to include, Dataannotationsmodelvalidatorprovider is undoubtedly the most important, asp.net The declarative model validation provided by the MVC default based on the data annotation feature is implemented through the dataannotationsmodelvalidator provided by Dataannotationsmodelvalidatorprovider.

First, Validationattribute characteristics

Similar to the model metadata defined by the data annotation attribute, we can define the model validation rule by applying the corresponding annotation attribute on the data type and its attributes as model. All validation attributes are inherited directly or indirectly from the abstract type System.ComponentModel.DataAnnotations.ValidationAttribute. As the following code fragment shows, Validationattribute has a string-type ErrorMessage property that specifies a validation error message. For the sake of localization or the need for separate maintenance of error messages, we can use resource files to save error messages. In this case we only need to specify the name and type of the resource item that contains the error message through the Errormessageresourcename and Errormessageresourcetype properties.

   1:public Abstract class Validationattribute:attribute
2: {
3: Public string ErrorMessage {get; set;}
4: Public string Errormessageresourcename {get; set;}
5: Public Type Errormessageresourcetype {get; set;}
6: protected string errormessagestring {get;}
7:
8: Public Virtual String formaterrormessage (string name);
9:
A: Public virtual BOOL IsValid (object value);
One: protected virtual Validationresult IsValid (object value, Validationcontext validationcontext)
12:
: Public void Validate (object value, string name);
A: Public validationresult Getvalidationresult (object value, Validationcontext validationcontext);
15:}

Second, the definition of the validation message

If we specify a string as a validation error message through the ErrorMessage property, and the name and type of the error message resource item are specified by the Errormessageresourcename/errormessageresourcetype property, The latter has a higher priority. Validationattribute has a protected read-only property errormessagestring used to return the final error message text.

For the definition of the error message, we can define a complete message, such as "age must be between 18 and 25". However, for the case where the resource file is maintained independently of the error message, in order to maximize the reuse of the defined resource text, we tend to define a text template containing placeholders, such as "{DisplayName} must be in {lowerbound} and {Upperbound ", so that the message applies to all validation based on numeric ranges. For the latter, placeholders in the template can be replaced in virtual method formaterrormessage. The parameter name in the method actually represents the corresponding display name, that is, the DisplayName property of the corresponding modelmetadata.

The default implementation of the Formaterrormessage method in Validationattribute is simply to invoke the static method format of string to use the parameter name as the parameter to replace the placeholder, as defined below. So, by default, when we define the error message template, we only allow a placeholder "{0}" for the display name to be included. If you have additional placeholders, or you do not need a defined method based on ordinal ("{0}") (for example, a text-based placeholder like "{DisplayName}" is more readable), you only need to rewrite the Formaterrormessage method.

   1:public Abstract class Validationattribute:attribute
2: {
3: //other Members
4: Public Virtual String formaterrormessage (string name)
5: {
6: Return string. Format (CultureInfo.CurrentCulture, errormessagestring, new object[] {name});
7: }
8:}

III. implementation of validation

When we create our own validation features by inheriting Validationattribute, we can implement our custom validation logic by overriding the public method IsValid or the protected method IsValid. The reason we are able to rewrite any IsValid method is that our custom validation logic takes effect because the two methods are specifically defined in Validationattribute. As the two methods are defined in Validationattribute, there is a reciprocal invocation of the relationship, and this mutual invocation necessarily causes a "dead loop", so we need to rewrite at least one of the methods rather than avoid the "dead loop" method. The "Dead Loop" is quoted here because Validationattribute is handled internally and throws a NotImplementedException exception when that happens.

   1://Call public IsValid method
2:public class Validatorattribute:validationattribute
3: {
4: static void Main ()
5: {
6: Validatorattribute validator = new Validatorattribute ();
7: Validator. IsValid (New object ());
8: }
9:}
10:
11://Invoke protected IsValid method
12:public class Validatorattribute:validationattribute
13: {
: static void Main ()
: {
: Validatorattribute validator = new Validatorattribute ();
: Validator. IsValid (New object (), null);
: }
19:}

To validate the need for IsValid overrides of virtual methods, let's do a simple example demo. In a console application, we wrote a two-part program, where a validatorattribute was defined by inheriting Validationattribute, but no IsValid method was rewritten. When we run the two programs separately in debug mode, we throw the notimplementedexception exception shown in the following illustration, indicating that "this class has not implemented IsValid (object value)." The preferred entry point is Getvalidationresult (), and the class should override IsValid (object value, Validationcontext context). ”

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.