custom unobtrusive date validators for dates

微笑、不失礼 提交于 2019-12-04 15:02:36
Robin van der Knaap

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

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