ASP. MVC3 data Validation (iii)-Custom data annotations

Source: Internet
Author: User

Original: ASP. MVC3 data Validation (iii)-Custom data annotations

The first two sections are all about ASP. MVC3 Pre-set data annotations, but system free data annotations are definitely not suitable for all occasions, so sometimes we need to customize the data annotations.                                            There are two types of custom data annotations, one of which is written directly in the model object, and the advantage of this is that it is only necessary to care about the validation logic of a model object, and the disadvantage is that it cannot be reused.        Another is the encapsulation in the custom data annotations, the advantage is reusable, the disadvantage is the need to deal with different types of models. Now let's take a look at how to customize data annotations and use in ASP. Net. MvC3 with the method encapsulated in a custom data annotation.I. Validation of custom attribute levelsFirst, all data annotations should be inherited from theSystem.ComponentModel.DataAnnotations in the namespace.Validationattribute class. Rewrite itsprotected virtual validationresult IsValid (object value, validationcontext validationcontext); For example: We need to write a username of data that cannot exceed 10 letters (you might say it's not someStringlengthWell, just for example, I really didn't think of any other good examples of custom data annotations. (1) Create a new classMaxlengthattribute, the code is as follows:

    public class Mymaxlengthattribute:validationattribute    {        private readonly int MaxLength;         Public mymaxlengthattribute (int maxLength)        {            maxLength = maxLength;        }         protected override Validationresult IsValid (object value, Validationcontext validationcontext)        {            string Content = value. ToString ();            if (content. Length > MaxLength)            {                return new Validationresult ("Too many characters entered!") ^_^");            }            return validationresult.success;            Return base. IsValid (value, Validationcontext);        }
The second step is to use the same data annotations as you normally would with ASP. NET, such as:
        [Required (Errormessageresourcetype=typeof (errormessage), errormessageresourcename= "Userrequire")]        [Display (name = "user name")]        [Mymaxlengthattribute (Ten)]        [Remote ("Checkusername", "Account", httpmethod= "POST")]        public string UserName {get; set;}
Well, that's just two simple steps to make.

Validation results: For custom data annotations because they are inherited from theSystem.ComponentModel.DataAnnotations in the namespace.Validationattribute class, so some of its properties can also be used, such as errormessage, such as:
        [Required (Errormessageresourcetype=typeof (errormessage), errormessageresourcename= "Userrequire")]        [Display (name = "user name")]        [Mymaxlengthattribute (10,errormessage= "{0} has too many words")]        [Remote ("Checkusername", "Account", httpmethod= "POST")]        public string UserName {get; set;}
It is important to note that custom data annotations do not support client-side validation, and all data needs to be committed and then validated by the server, so if you want to implement client side validation at the same time, you need to write your own JS verification. However, there is a problem with this verification that the default authentication information does not implement the display Name directly, so the following changes are required:
    public class Mymaxlengthattribute:validationattribute    {        private readonly int MaxLength;         Public mymaxlengthattribute (int maxLength): base ("{0} has too many characters!")        {            MaxLength = MaxLength;        }         protected override Validationresult IsValid (object value, Validationcontext validationcontext)        {            string Content = value. ToString ();            if (content. Length > MaxLength)            {                //return new Validationresult ("Too many characters entered! ^_^");                String errormessage = Formaterrormessage (validationcontext.displayname);                 return new Validationresult (errormessage);            }            return validationresult.success;            Return base. IsValid (value, Validationcontext);        }    }
Validation results:

ii. Validation of the custom model level (Ivalidatableobject)This interface is designed to implement the model self-validation (self-validating), which is the new validation feature of ASP.        The difference between this feature and the common data annotation is that the common data annotations only validate one property of the model, and the self-validation of the Ivalidatableobject interface is validated at the model level, such as validating the relationship between several properties of the model.        For example, I want to verify that the password I entered two times is the same (OK, I'll write it again with the system's own verification). (1) First, you need to validate the model to implement the Ivalidatableobject interface. public class registermodel : ivalidatableobject (2) implemented in modelValidateMethod:
         Public Ienumerable<validationresult> Validate (validationcontext validationcontent)        {            if (Password! = ConfirmPassword)            {                yieldreturnnew Validationresult (" two input passwords are different!  "new"Password"  });            }        }

This method will automatically verify that the two input passwords are the same when the model is submitted, and will prompt if different, as follows:

Note: 1, self-validation can only write methods in the model that needs to be validated, so this self-validating code can not be reused; 2, the self-validating return value is IEnumerable<validationresult>Instead ofValidationresult, so the return value can be more than one validation error.            3. The Validate method does not pass in the value parameter, meaning that the Validate method can directly access the value of the property in the model. 4. The return value uses yield return to construct the enumeration return value, the second parameter is the property that specifies the error information binding, because it is a string array, so you can associate multiple properties. By the way the practice with the source of sharing, model part mainly in Registermodel, download please click: http://pan.baidu.com/share/link?shareid=143863&uk=4044128861

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.