Asp.net mvc3 data verification (III)-Custom Data Annotation

Source: Internet
Author: User
The first two sections talk about the pre-defined data annotation of Asp.net mvc3, but the free data annotation of the system is certainly not suitable for all occasions, so sometimes we need to customize the data annotation. There are two types of Custom Data annotations. One is to write them directly in the model object. The advantage of this is that you only need to care about the validation logic of one model object during verification, and the disadvantage is obvious, that is, it cannot be reused. Another type of data is encapsulated in custom data annotations. The advantage is that the data can be reused. The disadvantage is that different types of models need to be used. Now let's take the method encapsulated in the Custom Data annotation as an example to see how to customize and use the data annotation in Asp.net mvc3. 1. custom attribute Level VerificationFirst, all data annotations should inherit from the validationattribute class in the system. componentmodel. dataannotations namespace. Override its protected virtual validationresult isvalid (object value, validationcontext); for example, we need to write a data Annotation with a username of no more than 10 letters (You may say this is not the stringlength, well, just take this as an example. I really didn't expect other good examples that require Custom Data annotations ). (1) create a maxlengthattribute class. The Code is as follows:

Public class values: validationattribute {private readonly int maxlength; Public mymaxlengthattribute (INT maxlength) {maxlength = maxlength;} protected override validationresult isvalid (object value, validationcontext) {string content = value. tostring (); If (content. length> maxlength) {return New validationresult ("too many characters are entered! ^_^ ");} Return validationresult. success; // return base. isvalid (value, validationcontext );}
The second step is to use the data annotation provided by Asp.net normally, for example:

[Required (errormessageresourcetype = typeof (errormessage), errormessageresourcename = "userrequire")] [display (name = "username")] [mymaxlengthattribute (10)] [remote ", "Account", httpmethod = "Post")] Public String username {Get; set ;}
Well, you only need to do this in two simple steps.

Verification Result: The Custom Data annotation is inherited from the validationattribute class in the system. componentmodel. dataannotations namespace, so some of its attributes can also be used, such as errormessage, such:
[Required (errormessageresourcetype = typeof (errormessage), errormessageresourcename = "userrequire")] [display (name = "username")] [mymaxlengthattribute (10, errormessage = "{0} too many words")] [Remote ("checkusername", "Account", httpmethod = "Post")] Public String username {Get; set ;}
Note that custom data Annotations do not support client-side verification. All data needs to be submitted before server-side verification. Therefore, if you want to implement client-side verification at the same time, you need to write your own JavaScript verification. However, there is a problem with such verification, that is, the default verification information cannot be directly displayed with the display name, 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) {string content = value. tostring (); If (content. length> maxlength) {// return New validationresult ("too many characters are entered! ^_^ "); String errormessage = formaterrormessage (validationcontext. displayname); return New validationresult (errormessage);} return validationresult. success; // return base. isvalid (value, validationcontext );}}
Verification Result:

  Ii. Custom model-level verification (ivalidatableobject)This interface is used to implement self-Validating of the model and is a new verification feature of Asp.net mvc3. The difference between this feature and common data annotation is that common data annotation can only verify one attribute of the model, while self-verification of the ivalidatableobject interface is performed at the model level, for example, verify the relationship between several attributes of the model. For example, I want to verify that the two passwords are the same (well, I will write the built-in verification again ). (1) first, implement the ivalidatableobject interface of the model to be verified. Public class registermodel: ivalidatableobject (2) Implement the validate method in model:
Public ienumerable <validationresult> validate (validationcontext validationcontent) {If (password! = Confirmpassword) {yield return New validationresult ("the two passwords are different! ", New [] {" password "});}}

 

This method automatically verifies whether the two passwords are the same when the model is submitted. If the passwords are different, a prompt is displayed, as shown below:

Note: 1. Self-verification can only write the method in the model to be verified, so this self-Verification Code cannot be reused; 2. the return value of self-verification is ienumerable <validationresult>, instead of validationresult, therefore, the return value can contain more than one verification error. 3. The value parameter is not input to the validate method, which means that the validate method can directly access the attribute values in the model. 4. The returned value uses yield return to construct the enumerated return value. The second parameter specifies the attribute bound to the error message. Because it is a string array, multiple attributes can be associated. By the way to share the exercise with the source code, the model part is mainly in registermodel, download please CLICK: http://pan.baidu.com/share/link? Consumer id = 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.