ASP. net mvc through Model verification helps us easily implement data verification. By default, ValidationAttribute-based declarations are used for verification, we only need to apply the corresponding ValidationAttribute to the type or attribute of the Model. For custom verification, we only need to define the corresponding Validation. However, the server-side verification is relatively simple, and the client-side verification is slightly more complex, this article provides a simple example to describe in ASP.. net mvc. [Source code download from http://www.bkjia.com/uploadfile/2012/0521/20120521142420339.rar]
I. AgeRangeAttribute
It is used to verify the date of birth field to ensure that the AgeRangeAttribute of the age is defined as follows. For simplicity, we directly let it inherit from RangeAttribute. The server verification logic is defined in the overwritten IsValid method, and the FormatErrorMessage method is rewritten to generate verification messages for ages. AgeRangeAttribute implements the IClientValidatable interface and generates client verification rules in the implemented GetClientValidationRules method. The ModelClientValidationRule object of the generated type "agerange" contains three parameters (currentdate, minage, and maxage), indicating the current date (used for age calculation) and the allowed age range, respectively.
1: public class AgeRangeAttribute: RangeAttribute, IClientValidatable
2 :{
3: public AgeRangeAttribute (int minimum, int maximum)
4: base (minimum, maximum)
5 :{}
6:
7: public override bool IsValid (object value)
8 :{
9: DateTime birthDate = (DateTime) value;
10: DateTime age = new DateTime (DateTime. Now. Ticks-birthDate. Ticks );
11: return age. Year >=( int) this. Minimum & age. Year <= (int) this. Maximum;
12 :}
13:
14: public override string FormatErrorMessage (string name)
15 :{
16: return base. FormatErrorMessage ("Age ");
17 :}
18:
19: public IEnumerable <ModelClientValidationRule> GetClientValidationRules (ModelMetadata metadata, ControllerContext context)
20 :{
21: ModelClientValidationRule validationRule = new ModelClientValidationRule () {ValidationType = "agerange", ErrorMessage = FormatErrorMessage (metadata. DisplayName )};
22: validationRule. ValidationParameters. Add ("currentdate", DateTime. Today. ToString ("dd-MM-yyyy "));
23: validationRule. ValidationParameters. Add ("minage", this. Minimum );
24: validationRule. ValidationParameters. Add ("maxage", this. Maximum );
25: yield return validationRule;
26 :}
27 :}
Ii. Client registration verification method
Because ASP. net mvc uses JQuery Validation for client verification, we can use the following javascript to register the function for client verification and add the corresponding adapter. The function added to jQuery. validator for age range verification has three parameters (value, element, and params) representing the verified value, element, and input parameters respectively. The three values (current date, minimum age range, and maximum value) required by the Verification logic are obtained through the params parameter. This parameter is actually obtained from the verification rule generated by the GetClientValidationRules method defined above when the adapter is added.
1: jQuery. validator. addMethod ("agerange ",
2: function (value, element, params ){
3:
4: var minAge = params. minage;
5: var maxAge = params. maxage;
6:
7: var literalCurrentDate = params. currentdate;
8: var literalBirthDate = value;
9: var literalCurrentDates = literalCurrentDate. split ('-');
10: var literalBirthDates = literalBirthDate. split ('-');
11:
12: var birthDate = new Date (literalBirthDates [2], literalBirthDates [1], literalBirthDates [0]);
13: var currentDate = new Date (literalCurrentDates [2], literalCurrentDates [1], literalCurrentDates [0]);
14: var age = currentDate. getFullYear ()-birthDate. getFullYear ();
15: return age> = minAge & age <= maxAge
16 :});
17:
18: jQuery. validator. unobtrusive. adapters. add ("agerange", ["currentdate", "minage", "maxage"], function (options ){
19: options. rules ["agerange"] = {
20: currentdate: options. params. currentdate,
21: minage: options. params. minage,
22: maxage: options. params. maxage
23 :};
24: options. messages ["agerange"] = options. message;
25 :});
3. Application of AgeRangeAttribute
Now we apply AgeRangeAttribute to a simple ASP. net mvc application. In ASP. in the empty Web application created by the net mvc Project template, we define a simple Person type. The AgeRangeAttribute we define is applied to the BirthDate that represents the birth date, set the upper and lower limits of age to 18 and 30.
1: public class Person
2 :{
3: [DisplayName ("name")]
4: public string Name {get; set ;}
5:
6: [AgeRange (18, 30, ErrorMessage = "{0} must be between {1} and {2! ")]
7: [DisplayName ("Date of Birth")]
8: [DisplayFormat (ApplyFormatInEditMode = true, DataFormatString = "{0: dd-MM-yyyy}")]
9: public DateTime? BirthDate {get; set ;}
10 :}
Then we add the next HomeController. In the default Action method Index, we will display the created Person object in the default View.
1: public class HomeController: Controller
2 :{
3: public ActionResult Index ()
4 :{
5: return View (new Person {BirthDate = DateTime. Today, Name = "Foo "});
6 :}
7: [HttpPost]
8: public ActionResult Index (Person person)
9 :{
10: return View (person );
11 :}
12 :}
The code snippet shown below represents the View definition. The extension method EditorModel of HtmlHelper <TModel> is called directly to render the Model's Person object in the editing mode in a form. Finally, do not forget to include javascript files that contain the preceding javascript fragments in the Layout file.
1: @ model Person
2: @ using (Html. BeginForm ())
3 :{
4: @ Html. EditorForModel ()
5: <input type = "submit" value = "Save"/>
6 :}
Run our program, enter an invalid date of birth, and click "Save" to submit the form (for the first client verification). The client verification will take effect, as shown in.
Author: Artech