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