KaioMartins KaioMartins - 10 months ago 64
ASP.NET (C#) Question

Edit a function in Jquery.validate.js validation for date dd/mm/yyyy

I'm having a problem to validate the date field in my system (asp.net). I already standardized the fields in the class with annotations:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]

It's working quite good, showing me the fields like i want, but when i try to edit, the forms show me a error like this:

The field [field] must be a date.

So i can't save the editions because it's doesn't pass by the jquery validator.

I've standardized in c# annotations to dd/mm/yyy but the jquery is set to mm/dd/yyyy.

During my tests, i found (i guess) that one of this files is that one which makes the validation for the date field in the forms:

  • jquery.validate.js

  • jquery.validate.unobtrusive.js

I found this because when i remove this scripts from the page, the validation doesn't work, but i'm not sure also if this scripts call anothers.

And in the jquery.validate.js i found this functions and i tried to edit it in many ways, but without success:

date: function( value, element ) {
return this.optional(element) || !/Invalid|NaN/.test(new Date(value).toString());

dateISO: function( value, element ) {
return this.optional(element) || /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(value);

I'm not sure that i'm modifying the right thing, so i need a hand here, please.

As i don't know what to modify, here's the link to jquery.validate.js.


Answer Source

You can write your own parser function, as @RobG suggested, OR you can modify the original one, if you don't use it in your page. I use old versions of Globalize plugin and there was some functions to change the 'language' for validation plugin, as numbers with 1.234,56 format (instead standard 1,234.56 english format) and so on...

In your case, you can use:

$.validator.methods.date = function (value, element) { /* place your function here */ }

to override the default behavior.

And you can find reg expr for dd/MM/yyyy here: Regex to validate date format dd/mm/yyyy

EDIT: Where do you do this? Ok, in your own javascript code, just after load jquery.validate plugin. You can wait to onReady event, too.

<script src="jquery.validate.min.js"></script>
        $.validator.methods.date = ...