MVC custom validation: compare two dates MVC custom validation: compare two dates jquery jquery

MVC custom validation: compare two dates


You need to modify your client-side script to check for the tested element's prefix, and add the prefix (if any) to your selector, as follows:

$.validator.addMethod("isdateafter", function(value, element, params) {    var parts = element.name.split(".");    var prefix = "";    if (parts.length > 1)        prefix = parts[0] + ".";    var startdatevalue = $('input[name="' + prefix + params.propertytested + '"]').val();    if (!value || !startdatevalue)         return true;        return (params.allowequaldates) ? Date.parse(startdatevalue) <= Date.parse(value) :        Date.parse(startdatevalue) < Date.parse(value);});


Do not forget to include the client side inside this code. It tooks me hours to find that this was missing!

(function ($) {  // your code here..})(jQuery);


Just to fix a small error in counsellorben's javascript: the "(params.allowequaldates)" will be interpreted as a string (which will have a value of "False" or "True"), but that string will always be evaluated to true, thus always allowing equal dates.If you also want to allow for more levels of nesting of your objects than just 1, then you will get:

$.validator.addMethod("isdateafter", function(value, element, params) {    var parts = element.name.split(".");    var prefix = "";    for (var i = 0; i < parts.length - 1; i++)       prefix = parts[i] + ".";    var startdatevalue = $('input[name="' + prefix + params.propertytested + '"]').val();    if (!value || !startdatevalue)         return true;        var allowequal = params.allowequaldates.toLowerCase === "true";    return allowequal ? Date.parse(startdatevalue) <= Date.parse(value) :        Date.parse(startdatevalue) < Date.parse(value);});