asp.net mvc helps us easily validate data by using model validation, which, by default, is based on the Validationattribute declaration that validation is used, We just need to apply the corresponding Validationattribute to model type or attribute. For custom validation, we just need to define the appropriate validation, but the server-side validation is simpler, and the client validation is slightly more complex, and this article provides a simple example of the basic steps to implement custom validation in asp.net mvc. [Source code download from here]
First, Agerangeattribute
The Agerangeattribute definition used to validate the birth date field to ensure that the age is within the defined range is as follows, and we simply let it inherit directly from Rangeattribute. The server-side validation logic is defined in the overridden IsValid method, and the Formaterrormessage method is overridden to generate an age-specific validation message. The Agerangeattribute implements the Iclientvalidatable interface and generates client-side validation rules in the implemented Getclientvalidationrules method. The Modelclientvalidationrule object of the generated type "Agerange" contains three parameters (CurrentDate, Minage, and MaxAge), representing the current date (used to calculate the age), and the range of allowable ages.
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", Error message= 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:}
Registration of Client Authentication methods
Because ASP.net mvc uses the jquery validation for client-side validation, we can register the function to implement client-side validation and add the corresponding adapter by using this JavaScript section below. The function that is added to the jquery.validator for age-scoped validation has three parameters (value, element, params) representing the validated value, element, and incoming arguments, respectively. Validation logic must have three numeric values (current date, minimum age range, and maximum value) obtained by parameter params. This parameter is actually obtained from the validation rules generated by the Getclientvalidationrules method defined above when adding adapter.
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:});