The field Date must be a date error in MVC Application

When I working on a project one of dev in my team asked me that scaffolded views in MVC is not accepting date when using jQuery date validation plugin which is default shipped with MVC template.

Here is the screenshot:
This is what being used in the application to localize the date settings and no other changes so far.

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

After little effort I found the solution. Basically, this issue is related with all Webkit based web browsers. The best solution for me was to override the validate date function from jquery.validate.js.

Here is the steps to resolve this:

Step 1

Create a new jquery.validate.date.js file.

Step 2

Use following code inside that file.

$(function () {
    $.validator.methods.date = function (value, element) {
        if ($.browser.webkit) {
            var d = new Date();
            return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
        }
        else {
            return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
        }
    };
});

Step 3

Now ensure that it is loaded after jquery.validate.js file, look at this:
Now run the project you will not see this issue.

Hope this helps.

Comments

  1. but it stops all Property Validations..how to overcome with it.

    ReplyDelete
  2. Even I am facing the same problem. Validation breaks if we use this solution.

    ReplyDelete
  3. $.browser was deprecated in jQuery 1.9 and no longer exists

    ReplyDelete

Post a Comment

Popular posts from this blog