custom unobtrusive date validators for dates

好久不见. 提交于 2019-12-09 22:32:48

问题


Maybe it's just the way my mind works, but I have a very hard time understanding how you're supposed to do custom unobtrusive validators. The C# part is easy enough, but the jqueryui adapters are where i get lost.

I've been trying to make a validator that requires a date to be a certain amount of time in the past. I use this for age validation, to make sure someone has entered a date that is 18 years in the past.

I finally decided to just make it a remote validator, that way the validation uses the same code both client and server side. Still, i'd be interested in the jquery to make this work.

I wish the Data Annotation Extensions had date functions.


回答1:


You can find a lot of information in Brad Wilson's blog article about unobtrusive validation with asp.net mvc, including creating custom validators.

Based on the following html (should be the output of the TextBox helper)

    <input type="text" name="Age"
        data-val="true" 
        data-val-required="This field is required" 
        data-val-minage="You should be 18 years or older, go get your parents!" 
        data-val-minage-value="18" />
    <input type="submit"/>

You can add the following javascript to get things validated on the client side:

    // Extend date with age calculator
    Date.prototype.age = function (at) {
        var value = new Date(this.getTime());
        var age = at.getFullYear() - value.getFullYear();
        value = value.setFullYear(at.getFullYear());
        if (at < value) --age;
        return age;
    };

    // Add adapter for minimum age validator. Wrap in closure
    (function ($) {
        $.validator.unobtrusive.adapters.addSingleVal("minage", "value");
    } (jQuery));

    // Add client side minimum age validator
    $.validator.methods.minage = function (value, element, params) {

        // If no value is specified, don't validate
        if (value.length == 0) {
            return true;
        }

        var dob = new Date(Date.parse(value));

        if (dob.age(new Date()) < params || dob == 'Invalid Date') {
            return false;
        }

        return true;
    };

Credits for the age calculator are due to Dave

The one thing missing here is globalization, but I figured it was out of the question's scope. btw very easy to implement using the jquery Globalize plugin

Hope this helps



来源:https://stackoverflow.com/questions/7210887/custom-unobtrusive-date-validators-for-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!