MVC validation 04-Custom validation rules, date range validation

Source: Internet
Author: User

Original: MVC validation 04-Custom validation rules, date range validation

This article experiences scope validation. Relevant to this article include:

MVC authentication 01-BASIC, Remote authentication
MVC validation 02-Custom validation rules, message validation
MVC validation 03-Custom validation rules, forbidden to enter certain values

When you need to verify the length of a string, you can use Stringlength:
[Stringlength (errormessage = "{0} must contain at least {2} characters. ", Minimumlength = 6)]

When you need to validate an array range, you can use range:
[Range (0,5)]

What if you need to validate a date range?
Suppose to validate the date with the current date as the base, the date between the current and seventh days as valid, and the other invalid.

Custom validation attributes, inheriting Validationattribute and implementing iclientvalidatable

The IsValid () method that overrides the base class Validationattribute is used for server-side validation.
Implementing the Iclientvalidatable interface method is to add a property to the front-end HTML element so that jquery detects it.

ExpandusingSystem;usingSystem.ComponentModel.DataAnnotations;usingSYSTEM.WEB.MVC;namespacemvcvalidation.extension{ Public classDayrangeattribute:validationattribute, iclientvalidatable {Private int_minday;Private int_maxday; PublicDayrangeattribute (intMinday,intMaxday) {if(Minday.compareto (Maxday) >-1) {Throw NewException ("The minimum date cannot be greater than or equal to the maximum date"); } This. _minday = Minday; This. _maxday = Maxday; } Public Override BOOLIsValid (Object value)        {if(value==NULL)return true; var comparedate =value  asDateTime?;if(comparedate.hasvalue) {comparedate = compareDate.Value.Date;returnComparedate.value >= DateTime.Today.AddDays (_minday). Date && comparedate.value <= DateTime.Today.AddDays (_maxday).            Date; }return false; } PublicSystem.collections.generic.ienumerable<modelclientvalidationrule> Getclientvalidationrules (ModelMetadata metadata, ControllerContext context) {var rule =Newmodelclientvalidationrule {ValidationType = "Dayrange",//The Dayrange will eventually become the Data-val-dayrange attribute is detected by jqueryErrorMessage = formaterrormessage (metadata. GetDisplayName ())};//Here the Min and Max will be the parameters of the jquery validation extension methodRule. Validationparameters["min"] = _minday; Rule. Validationparameters["Max"] = _maxday; YieldreturnRule }    }}

Attention:
ValidationType = "Dayrange" in the dayrange must be lowercase, otherwise error.
ValidationType = "Dayrange" eventually becomes an attribute data-val-dayrange of the HTML element, which can be distinguished by jquery detection.
Rule. validationparameters["min") and rule. validationparameters["Max"],min and Max will be used as parameters for the jquery extension method, and of course it must be lowercase.

To hit the custom validation feature on the view model

[Dayrange (0, 7)] verifies the date within the day to the seventh day.

Expand  Public classRegistermodel {[Required] [Stringlength (6, minimumlength = 2)]//Plus[Display (Name = "User name")]//[remote ("Checkusername", "Validate", errormessage = "Remote Authentication user name failed")][Noinput ("Demo,jack", errormessage ="This name cannot be used")] Public stringUserName {Get;Set; } [Required] [DataType (datatype.emailaddress)] [Display (Name = "Mail")]//[email]         Public stringEmail {Get;Set; } [Dayrange (0, 7)] [Display (Name = "class Time")] PublicDateTime Classdate {Get;Set; } [Required] [stringlength (errormessage = "{ 0} field minimum {2} characters, up to {1} characters", Minimumlength = 6)] [DataType (Datatype.password)] [Display (Name ="Password")] Public stringPassword {Get;Set; } [DataType (Datatype.password)] [Display (Name = "Confirm Password")] [System.ComponentModel.DataAnnotations.Compare ("Password", errormessage ="The password and confirmation password do not match. ")] Public stringConfirmPassword {Get;Set; }

Extended jquery Validation JQuery.validator.dayrange.js

Extended jquery Validation method
The first parameter is the value of the front-end input
The second argument is an HTML element
The third parameter is a custom validation attribute Dayrangearribute rule.validationparameters["min" and rule. Validationparameters[the key value of "Max"]
JQuery.validator.addMethod (' dayrange ', function (value, element, param) {
    if (! value) {
        return false;
    }
    Value:1999/1/1
    value. Split ('-');
    New Date ();
    New Date ();
    New Date ();
    New Date (Valuedateparts[2],
                        (Valuedateparts[1]-1),
                         Valuedateparts[0],
                         Now.gethours (),
                         Now.getminutes (),
                         (Now.getseconds () + 5));
    Mindate.setdate (Mindate.getdate ()-parseint (param.min));
    Maxdate.setdate (maxdate.getdate () + parseint (Param.max));
    return dateValue >= mindate && dateValue <= maxdate;
});
The first parameter is a jquery validation extension method name
The second and third parameters are the minimum or maximum values, respectively
The third parameter is the value corresponding to ValidationType in Dayrangeattribute
JQuery.validator.unobtrusive.adapters.addMinMax (' dayrange 'min'max'dayrange ' );

register.cshtml View

Expand@model mvcvalidation.models.registermodel@{viewbag.title = "Register";} class="title> using (Html.BeginForm ())        {@Html. AntiForgeryToken () @Html. ValidationSummary () <fieldset> <legend> Registration Form </legend> <ol> <li> @Html. labelfor (M = m.username) @Html. Textboxfor (M                + m.username) </li> <li> @Html. labelfor (M = m.email) @Html. textboxfor (M = m.email) </li> <li> @Html. labelfor (M = M.                classdate) @Html. textboxfor (M = m.classdate) </li> <li>            @Html. labelfor (M = M.password) @Html. passwordfor (M = m.password) </li> <li> @Html. labelfor (M = M.confirmpassword) @Html. passwordfor (M = M.confirmpa ssWOrd) </li> </ol> <input type= "Submit"value="Register"/> </fieldset>} @section Scripts {@Scripts. Render ("~/bundles/jqueryval") <script src="~/scripts/jquery.validator.dayrange.js"&GT;&LT;/SCRIPT&GT;}

Effect:

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.