2

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 ?

Chlebta
  • 3,090
  • 15
  • 50
  • 99

2 Answers2

3

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

Community
  • 1
  • 1
Harmon
  • 59
  • 2
0

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

Uroš Goljat
  • 1,806
  • 14
  • 15