Tuesday, January 21, 2014

How to validate dd/MM/yyyy date format in ASP.NET MVC client validations.

The problem is JQUERY validation does not consider the culture when performing the validation. So that, it will show you "Invalid date format" error message whenever you try to submit a form with a date field, which has the format of dd/MM/yyyy.

To fix the issue we can override the default validation behavior by including JQUERY Globalization plugin.

Right click on the application on in Visual Studio and select Manage NuGet Packages.

Then type globalize on search text box and install the package, which appears on the search results.

Finally, add the below script before the body closing tag on your page.

    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    <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");

No comments:
Write comments
Recommended Posts × +