jQuery date validation MVC 4 .Net 4.5.1 UK date “must be a date” Error

≡放荡痞女 提交于 2019-11-28 12:19:10

Changing the date validation method in jQuery.validate.js to the follwing solved the issue:

date: function (value, element) {
        $.culture = Globalize.culture("en-GB");
        var date = Globalize.parseDate(value, "dd/MM/yyyy", "en-GB");
        return this.optional(element) || 
                       !/Invalid|NaN/.test(new Date(date).toString());
    }

Tested in Chrome, FF and IE

in The Jquery which is calling simply add the format.

$(function() { $("#datepicker").datepicker({dateFormat: 'dd/mm/yy'}); });

http://www.matthewcarlin.co.uk/jquery-quick-tip-2-changing-date-format

Having just had to figure this out, I overrode the rule and used a data attribute

if (typeof jQuery.validator.methods.date !== 'function') {
    var f = function (value, element) {
        var e = $(element).attr('data-dateformat');
        if (e && (e.length)) {
            var dt = jQuery.datepicker.parseDate(e, value);
            return this.optional(element) || !/Invalid|NaN/.test(dt.toString());
        } else {
            return this.optional(element) || !/Invalid|NaN/.test(new Date(value).toString());
        }
    }
    jQuery.validator.addMethod("date", f);
} else {
    var m = jQuery.validator.methods.date;
    var f = function(value, element) {
        var e = $(element).attr('data-dateformat');
        if (e && (e.length)) {
            var dt = jQuery.datepicker.parseDate(e, value);
            return this.optional(element) || !/Invalid|NaN/.test(dt.toString());
        } else {
            return m(value, element);
        }
    }
    jQuery.validator.addMethod("date", f);
}

It ASSUMES you have datepicker, but if you are using dates, and jQuery, I think that's a safe bet. If the element has a date format defined in data-dateformat it will parse it using that, otherwise it will fall back to the default date rule, and if that wasn't present it implements the default rule.

I placed this in my site global code file to keep it outside the jQuery scripts

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