Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top