How ASP. NET MVC implements custom validation (server side validation + client authentication)

Source: Internet
Author: User

ASP. NET MVC helps us easily validate data by using model validation, and, by default, Validationattribute-based claims are verified to be used, and we only need to To apply the corresponding validationattribute to the model type or attribute. For custom validation, we just need to define the appropriate validation, but the server-side validation is relatively simple, and client authentication is a little more complicated, this article provides a simple example of the basic steps of implementing custom Validation in ASP. [Source code download from here]

First, Agerangeattribute

The Agerangeattribute definition for verifying the date of birth field to ensure that the age is within the defined range is as follows, for simplicity, we directly inherit it 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. Agerangeattribute implements the Iclientvalidatable interface and generates a client-side validation rule in the implemented Getclientvalidationrules method. The Modelclientvalidationrule object with the generated type "Agerange" contains three parameters (CurrentDate, Minage, and MaxAge), representing the current date (for calculating age) and the range of allowable ages.

   Class Agerangeattribute:rangeattribute, iclientvalidatable
   2: {
   3: Public     agerangeattribute (int maximum) 
   4:         Base (minimum, maximum)
   5:     {}
   
   7:     bool IsValid (value) 
   8:     {
   9:         datetime birthDate = (datetime)value;
  :         New DateTime (datetime.now.ticks-birthdate.ticks);
  One:         return age. Year >= (int.) This. Minimum && age. Year <= (int.) This. Maximum;    
  :     }
  
  +:     string formaterrormessage (string name) 
  :     {
  :         base. Formaterrormessage ("age"); 
  :     }
  
  : Public     ienumerable<modelclientvalidationrule> getclientvalidationrules (Modelmetadata metadata , ControllerContext context)
  :     {
  :         "Agerange", errormessage= formaterrormessage (metadata. DisplayName)};
  :         validationRule.ValidationParameters.Add ("currentdate", DateTime.Today.ToString ("dd-mm-yyyy")); 
  At:         validationRule.ValidationParameters.Add ("Minage", this. Minimum); 
  :         validationRule.ValidationParameters.Add ("MaxAge", this. Maximum); 
  :         return validationRule;
  :     }
  27:}

second, the registration of client authentication method

Since ASP. NET MVC uses 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 as follows. The function that is added to Jquery.validator for age-range validation has three parameters (value, element, params) that represent the validated values, elements, and incoming parameters, respectively. The validation logic must have three values (current date, minimum age range, and maximum value) obtained through the parametric 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",
   params) {
   3:     
   4:     params.minage;
   5:     params.maxage;
   
   7:     params.currentdate;
   8:     var literalbirthdate = value;
   9:     var literalcurrentdates = literalcurrentdate.split ('-'); 
  :     var literalbirthdates = literalbirthdate.split ('-'); 
  
  :     new Date (literalbirthdates[2], literalbirthdates[1], literalbirthdates[0]);
  :     new Date (literalcurrentdates[2], literalcurrentdates[1], literalcurrentdates[0]);
  :     var age = Currentdate.getfullyear ()-birthdate.getfullyear ();
  :     return age >= minage && age <= maxAge
  16:});
  
  18:jquery.validator.unobtrusive.adapters.add ("Agerange", [function (options) { 
  :     options.rules["Agerange"] = {
  :         currentdate:options.  Params.currentdate,
  £         minage:options.  Params.minage,
  A:         maxage:options.  Params.maxage
  :     };
  :     options.messages["agerange"] = Options.message;
  25:});

third, the application of Agerangeattribute

Now we're going to apply Agerangeattribute to a simple ASP. NET MVC application. In an empty web app created with the ASP. NET MVC project template, we define a simple person type, our defined Agerangeattribute applied to the birthdate that represents the date of birth, and will allow the age, The lower limit is set to 18 and 30.

   Class Person
   2: {
   3:     [DisplayName ("name")]
   4:     string Name {get; set;}
   
   6:     "{0} must be between {1} and {2}!" ")]   
   7:     [DisplayName ("date of birth")]
   8:     "{0:dd-mm-yyyy}")]
   9: Public     DateTime? BirthDate {get; set;}
  10:}

Then we add the following HomeController, in the default action method index we will create the person object in the default view.

   Class Homecontroller:controller
   2: {
   3: Public     actionresult Index ()
   4:     {
   5:         return View ("Foo"}); 
   6:     }
   7:     [HttpPost]
   8: Public     ActionResult Index ( person person)
   9:     {
  Ten:         return View (person);
  One:     }
  12:}

The code snippet shown below represents the definition of view, and we call the htmlhelper<tmodel> extension method directly Editormodel renders the person object as model in edit mode in a form. Finally, don't forget to include the JS file containing the above JavaScript snippet in the layout file.

   1: @model person
   2: @using (Html.BeginForm ())
   3: {     
   4:     @Html. Editorformodel ()
   5:     <typevalue/>   
   6:}

Run our program, enter an illegal date of birth and click on the "Save" button to submit the form (for first client authentication), the client validation will take effect, as shown in.

How ASP. NET MVC implements custom validation (server side validation + client authentication)

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.