7

This question has been asked before but the answers do not solve my problem. The problem is that I am always getting the following error with datetime field.

The field Created Time must be a date.

My Try

Here is modal where I have set date format

[Display(Name = "Created Time")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> CreatedTime { get; set; }

View code

<div class="form-group">
    @Html.LabelFor(model => model.CreatedTime, "Timesheet Date")
    <div class='input-group date' id='Datetimepicker1'>
        @Html.TextBoxFor(model => model.CreatedTime, new { @class = "form-control" })
        <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span>
    </div>
    @Html.ValidationMessageFor(model => model.CreatedTime, "", new { @class = "text-danger" })
</div>

In js

$('#CreatedTime').removeAttr("data-val-date");
$('#Datetimepicker1').datetimepicker({ format: 'DD/MM/YYYY' });

Also tried to change in jquery.validate.js funcation date: function (value, element) as below but but unable to solve the issue.

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

Visited links

The field must be a date - DatePicker validation fails in Chrome - mvc

The field date must be a date in mvc in chrome

And many more links and sites but unable to solve issue

Community
  • 1
  • 1
  • Which date picker are you using - jquery-ui? (and do not use `$('#CreatedTime').removeAttr("data-val-date");`) –  May 23 '15 at 06:24
  • @StephenMuecke I am using bootstrap datetimepicker to display date –  May 23 '15 at 06:25
  • Refer [this answer](http://stackoverflow.com/questions/27285458/jquery-ui-datepicker-and-mvc-view-model-type-datetime/27286969#27286969) - try adding the script after you load jquery and bootstrap (but not inside document.ready) –  May 23 '15 at 06:28

2 Answers2

4

Try it

Keep this js code out side of $(document).ready();. only inside of <script>Here</script> tag.

    $(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;
        });
        $("#ID").datepicker({ dateFormat: 'dd/mm/yy', changeYear: true });
    });    

Hope it will be helpful. In my case it is working.

Govinda Rajbhar
  • 2,926
  • 6
  • 37
  • 62
  • I have put this code inside of document.ready function but not working –  May 23 '15 at 06:39
  • Please put this code outside of document.ready function. just put it inside of tag than it will be working hope so. – Govinda Rajbhar May 23 '15 at 06:41
  • @GovindaRajbhar, You need to edit you answer and remove the `$(function () {`line –  May 23 '15 at 07:41
  • @StephenMuecke sorry but when I remove your suggested line than getting error :- `$(...).datepicker is not a function` so i am not removing it. – Govinda Rajbhar May 23 '15 at 08:48
  • That would depend on where you have rendered this in the view. As you have said yourself above it should not be in `document.ready` (`$(function ()` is a shortcut for `document.ready`). In your example, the last line (`$("#ID").datepicker({ ... });`) needs to be separated out and put inside `document.ready` if its not at the bottom of the page –  May 23 '15 at 08:56
1

This worked for me:

(Put that on _Layout.cshtml)

$(function () {
        $.validator.methods.date = function (value, element) {
            //Fix chrom Asp.Net MVC jQuery validation: The field "Myfield" must be a date.
            var ischrom = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase());
            if (ischrom) {
                if ($.browser.webkit) {
                    //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));
                }
            }
            else
            {
                return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
            }
        };

    });

credits to: http://blog.mohnady.com/2015/02/fix-aspnet-mvc-chrome-jquery-validation.html