The field date must be a date in mvc in chrome [duplicate]

霸气de小男生 提交于 2019-11-26 08:08:52

问题


I\'m doing a simple MVC4 Internet application, which allows to add some items to the categories.

Here is what i\'ve done so far.

I\'ve a datepicker in mvc view. The script for the datepicker is like this.

<script src=\"@Url.Content(\"~/Scripts/jquery-1.7.1.min.js\")\" type=\"text/javascript\"></script>
<script src=\"@Url.Content(\"~/Scripts/jquery-ui-1.8.20.min.js\")\" type=\"text/javascript\"></script>
@Scripts.Render(\"~/bundles/jqueryval\")
<script type=\"text/javascript\">
    $(function () {
        $(\'#dtItemDueDate\').datepicker({
            dateFormat: \'dd/mm/yy\',
            minDate: 0
        });
    });
</script>

My model property :

        [DisplayName(\"Item DueDate\")]
        [Required]
        [DisplayFormat(DataFormatString = \"{0:dd/MM/yyyy}\",ApplyFormatInEditMode = true)]
        [DataType(DataType.DateTime)]
        public DateTime? dtItemDueDate { get; set; }
        public char charCompleted { get; set; }

and in my view i\'ve done this:

@Html.TextBoxFor(m => m.dtItemDueDate)
@Html.ValidationMessageFor(m => m.dtItemDueDate)

The error is like this:

The field Item DueDate must be a date.

The strange this is that it does work in IE and mozilla, but doesnot work in Chrome.

I found many posts on SO, but none of them help

Any ideas/suggestions ?


回答1:


Editor note: This answer is no longer valid, as of jQuery 1.9 (2013) the $.browser method has been removed


According to this post it's a known quirk with Webkit-based browsers.

One solution is to modify jquery.validate.js by finding the function date: function (value, element) and put this code in it:

if ($.browser.webkit) {
    //ES - Chrome does not use the locale when new Date objects instantiated:
    var d = new Date();
    return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
}
else {
    return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
}



回答2:


Without changing jquery.validate.js, you can use the code snip below in $(document).ready():

jQuery.validator.methods.date = function (value, element) {
    var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
    if (isChrome) {
        var d = new Date();
        return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
    } else {
        return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
    }
};



回答3:


Rowan Freeman solution wont work for me since .toLocaleDateString(value) doesn't parse value strings

here's the solution i came up with => in jquery.validate.js find this function definition: "date: function (value, element)" and replace the code with:

// http://docs.jquery.com/Plugins/Validation/Methods/date
date: function (value, element) {
    var d = value.split("/");
    return this.optional(element) || !/Invalid|NaN/.test(new Date((/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) ? d[1] + "/" + d[0] + "/" + d[2] : value));
},



回答4:


Below is the working code that may helpful for some one to fix the date picker issue in chrome and safari: Model:

public DateTime? StartDate { get; set; }

View:

@Html.TextBoxFor(model => model.StartDate, "{0:dd/MM/yyyy}", new { @type = "text", @class = "fromDate" })

js:

$(function () {
    checkSupportForInputTypeDate();

    $('#StartDate').datepicker({        
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd/mm/yy'
    });    
});

//Function to configure date format as the native date type from chrome and safari browsers is clashed with jQuery ui date picker.
function checkSupportForInputTypeDate() {
    jQuery.validator.methods.date = function (value, element) {
        var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
        var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
        if (isSafari || isChrome) {
            var d = new Date();
            return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
        } else {
            return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
        }
    };
}



回答5:


Here's Maxim Gershkovich's solution spelled out a little more:

jQuery.validator.methods.date = function (value, element) {
    if (value) {
        try {
            $.datepicker.parseDate('dd/mm/yy', value);
        } catch (ex) {
            return false;
        }
    }
    return true;
};

Notes:

  • This depends on the jQuery datepicker method that comes with jQuery UI
  • This is actually more robust that the native date validation that comes with jQueryValidate.

    According to the docs on date validation:

    Returns true if the value is a valid date. Uses JavaScript's built-in Date to test if the date is valid, and therefore does no sanity checks. Only the format must be valid, not the actual date, eg 30/30/2008 is a valid date.

    Whereas parseDate will check that the date is valid and actually exists.




回答6:


I solved this issue by changing from DateTime to String.

This is the best solution for a good maintance that I can think at the moment.



来源:https://stackoverflow.com/questions/15706455/the-field-date-must-be-a-date-in-mvc-in-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!