1

i use mvc 5 but the jquery validate unobtrusive validates the date as MM/dd/yyyy and when i searched how to make it validates dd/MM/yyyy

i found jquery globalize to achieve this but i dont find any examples for the current version Globalize v1.1.2

All the examples i found is for the versions less than 1.x

The view

<div class="form-group">
    @Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Date, "dd/MM/yyyy", new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
    </div>
</div>

The metadata specified the date to be dd/MM/yyyy

    [Required(ErrorMessage = " الحقل مطلوب ")]
    [DisplayName("تاريخ ")]
    [DisplayFormat(DataFormatString = "{dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime Date { get; set; }

although that jquery validate unobtrusive validates the date as MM/dd/yyyy

enter image description here

Sparky
  • 98,165
  • 25
  • 199
  • 285
Mariam
  • 533
  • 2
  • 12
  • 22

1 Answers1

4

I had this problem before, you will need to overload jquery unobtrusive validation date validation method (as answered here), for it to know entered value is a date. By doing this you wont need to use jquery globalize.

code

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

        var ok = true;
        try {
            $.datepicker.parseDate('dd/mm/yy', value);
        }
        catch (err) {
            ok = false;
        }
        return ok;
    });

Otherwise if you set your application to use local culture you could then use this

 jQuery(function ($) {
        $.validator.addMethod('date', function (value, element) {
        var d = new Date();
        return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
        });
     });
Community
  • 1
  • 1
iAM
  • 1,365
  • 15
  • 25