Search code examples
asp.net-mvcdatejquery-validateglobalizationunobtrusive-validation

How to use jquery globalize with jquery validate unobtrusive in mvc 5


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


Solution

  • 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)));
            });
         });