Chlebta
Chlebta

Reputation: 3110

ASP.net MVC dateFormat Validation issue, Client side Validation

I want to get French date format dd/mm/yyyy working with my client side validation. I tried to use DataAnnotation like this :

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public Nullable<System.DateTime> DATE_NAISSANCE { get; set; }

But I'm geting always same problem Invalide Date Format if i put for example 15/09/2015, 30/12/2018... How to fix it ?

Upvotes: 2

Views: 2146

Answers (2)

Uroš Goljat
Uroš Goljat

Reputation: 1816

I you are also using jQuery UI, you can also use approach bellow:

$.validator.addMethod('date',
                function (value, element, params) {
                    if (this.optional(element)) {
                        return true;
                    }

                    var ok = true;
                    try {
                        // first parameter is date format, change this as needed 
                        $.datepicker.parseDate('dd/mm/yyyy', value);
                    } catch (err) {
                        ok = false;
                    }
                    return ok;
                });

This sample uses jQuery UI's datepicker function parseDate to check if entered date is in correct format.

Hope this helps!

Uros

Upvotes: 0

Harmon
Harmon

Reputation: 59

If you are using jQuery unobtrusive validation for the client side validation you could add a validator method, something like this:

$.validator.addMethod("date", function (value, element) {
    var bits = value.match(/([0-9]+)/gi), str;
    if (!bits)
        return this.optional(element) || false;
    str = bits[1] + '/' + bits[0] + '/' + bits[2];
    return this.optional(element) || !/Invalid|NaN/.test(new Date(str));
},
"Please enter a date in the format dd/mm/yyyy");

see this question:

Custom date format with jQuery validation plugin

Upvotes: 3

Related Questions