chamara chamara - 22 days ago 6
jQuery Question

Jquery dd/MM/yyyy date format validation

I using default ASP.NET MVC 4 validation bundle in my application. In view I have a date field in the format of "dd/MM/yyyy" and jquery validation failed to validate the format. Then I added the below code to override the default behavior.

$(function () {
$.validator.methods.date = function (value, element) {
Globalize.culture("en-GB");
// you can alternatively pass the culture to parseDate instead of
// setting the culture above, like so:
// parseDate(value, null, "en-AU")
return this.optional(element) || Globalize.parseDate(value) !== null;
}
});


Then the date validation issue was resolved, and now my application does not fire client side validation but the server side validation. what could be the reason for this behavior?

Answer

It was missing the globalize.js file. i modified the code as below and now working fine.

download the files from https://github.com/jquery/globalize

include references to relevant .js files (You can also install it with NuGet packages as well, which is the option I have used.)

<script src="~/Scripts/globalize/globalize.js"></script>
<script src="~/Scripts/globalize/cultures/globalize.culture.en-GB.js"></script>

$(document).ready(function () {
        $.culture = Globalize.culture("en-GB");
        $.validator.methods.date = function (value, element) {
            //This is not ideal but Chrome passes dates through in ISO1901 format regardless of locale 
            //and despite displaying in the specified format.

            return this.optional(element)
                || Globalize.parseDate(value, "dd/MM/yyyy", "en-GB")
                || Globalize.parseDate(value, "yyyy-mm-dd");
        }
    });
Comments