The first two sections are all asp.net mvc3 data annotations, but free data annotations are certainly 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 validation requires only concern for the validation logic of a model object, and the disadvantages are obvious, That is not reusable. another is encapsulated in a custom data annotation, the advantage is reusable, the disadvantage is the need to deal with different types of models. now, for example, we'll look at how you can customize data annotations in ASP.net mvc3 and use them in a way that encapsulates the custom data annotations. A, custom attribute-level validation first, all data annotations should inherit from the The Validationattribute class in the System.ComponentModel.DataAnnotations namespace. rewrite its protected virtual Validationresult isvalid (Object value, validationcontext validationcontext); For example: we needWrite a username that cannot be more than 10 letters (you might say this is not some stringlength, well, for example, I really didn't think of any other good examples of the need to customize data annotations). (1) Create a new class Maxlengthattribute with the following code:
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 ("There are too many characters entered.) ^_^");
}
return validationresult.success;
Return base. IsValid (value, Validationcontext);
}
The second step is to use the same data annotations as the normal use of 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 you can take.
Validation results: For custom data annotations that are inherited from the Validationattribute class in the System.ComponentModel.DataAnnotations namespace, some of its properties can also be used, such as errormess Age, such as:
[Required (Errormessageresourcetype=typeof (errormessage), errormessageresourcename= "Userrequire")]
[Display (name = "user name")]
[Mymaxlengthattribute (10,errormessage= "{0} Word too many words")]
[Remote ("Checkusername", "Account", httpmethod= "POST")]
public string UserName {get; set;}
Note that custom data annotations do not support client-side validation, and that all data needs to be submitted and then serviced. So if you want to implement client-side verification at the same time need to write JS verification. However, there is a problem with this validation 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): Too many characters for base ("{0}!")
{
MaxLength = MaxLength;
}
protected override Validationresult IsValid (object value, Validationcontext validationcontext)
{
string Content = value. ToString ();
if (content). Length > MaxLength)
{
//return new Validationresult ("There are too many characters entered.) ^_^");
String errormessage = Formaterrormessage (validationcontext.displayname);
return new Validationresult (errormessage);
}
return validationresult.success;
Return base. IsValid (value, Validationcontext);
}
Validation results:
Second, the custom model level of validation (Ivalidatableobject) This interface is to implement model self-validation (self-validating), is the ASP.net mvc3 new validation features. The difference between this feature and ordinary data annotation is that ordinary data annotations can only validate one attribute of model, and that the Ivalidatableobject interface is validated at the level of model, such as verifying the relationship between several attributes of model. For example, I would like to verify that the password entered two times is the same (well, I'll write the system again with the verification). (1) First, the need to verify the model to implement Ivalidatableobject interface. The public class Registermodel:ivalidatableobject (2) implements the Validate method in model:
Public ienumerable<validationresult> Validate (validationcontext validationcontent)
{
if (Password!= ConfirmPassword)
{
yield return new Validationresult ("two different passwords entered. ", new[] {" Password "});
}
This method automatically verifies that the password entered two times is the same when the model is submitted, and prompts if it is different, as follows:
Note: 1. Self-verification can only write the method in the model that needs to be validated, so this kind of self validated code cannot be reused; 2, the return value of the self validation is ienumerable<validationresult> instead of Validationresult , so the return value can have more than one validation error. 3, the Validate method does not pass in the value parameter, which means that the Validate method can directly access the property values in model. 4. The return value uses yield return to build the enumeration returned value, and the second parameter is the property that specifies the error message binding, because it is a string array, so you can associate multiple properties.
finally attach the usual regular expressions
Number: "^[0-9]*$".
N-bit number: "^\d{n}$".
Number of at least n digits: "^\d{n,}$".
Number of m~n digits:. "^\d{m,n}$"
0 and not 0 the beginning of the number: "^" (0|[ 1-9][0-9]*) $ ".
Positive real number with two decimal digits: ^[0-9]+ (. [ 0-9]{2})? $ ".
Positive real number with 1~3 decimal: "^[0-9]+ (. [ 0-9]{1,3})? $ ".
Non-zero positive integer: "^\+?" [1-9] [0-9]*$].
Non-zero negative integer: "^\-[1-9][]0-9" *$.
Characters of length 3: "^. {3}$ ".
A string of 26 English letters: "^[a-za-z]+$".
A string of 26 uppercase English letters: "^[a-z]+$".
A string consisting of 26 lowercase English letters: "^[a-z]+$".
A string consisting of numbers and 26 English letters: "^[a-za-z0-9]+$".
A string of numbers, 26 English letters, or underscores: "^\w+$".
Verify user password: "^[a-za-z]\w{5,17}$" is the correct format: start with a letter, length between 6~18, can only contain characters, numbers, and underscores.
Verify that there are ^%& ',; =?$\ ' and other characters: "[^%& ',; =?$\x22]+".
Only Chinese characters can be entered: "^[\u4e00-\u9fa5]{0,}$"
Verify email Address: "^\w+ ([-+.] \w+) *@\w+ ([-.] \w+) *\.\w+ ([-.] \w+) *$ ".
Verify InternetURL: "^http://([\w-]+\.) +[\w-]+ (/[\w-./?%&=]*)? $ ".
Verify phone Number: "^ (\ (\d{3,4}-) |\d{3.4}-)? \d{7,8}$" The correct format is: "Xxx-xxxxxxx", "xxxx-xxxxxxxx", "xxx-xxxxxxx", "xxx-xxxxxxxx", " XXXXXXX "and" XXXXXXXX ".
Verify ID Number (15-bit or 18-digit): "^\d{15}|\d{18}$".
Verify 12 months of the year: "^" (0?[ 1-9]|1[0-2]) $ "The correct format is:" 01 "~" 09 "and" 1 "~" 12 ".
Verify one months of 31 days: "^ (0?[ 1-9]) | ((1|2) [0-9]) |30|31) $ "correct format for;" 01 "~" 09 "and" 1 "~" 31 ".