简体   繁体   中英

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

I'm always getting the validation message like following when I submit the form to call post Action (Method)

The field PatientDOB must be a date.

My model is

[Required(ErrorMessage = "Patient DOB is required")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

My view is like the following,

@{
    Layout = "~/Views/Shared/_FormLayout.cshtml";
    var dob= Model.PatientDOB == DateTime.MinValue ? string.Empty : Model.PatientDOB.ToString("yyyy-MM-dd");
    var phoneNo = Model.PatientPhoneNo == 0 ? string.Empty : Model.PatientPhoneNo.ToString();
}

<div class="row">
    <div class="col-lg-2">
        <label class="m-t-sm font-bold">Date of Birth:</label>
    </div>
    <div class="col-lg-2">
        @Html.TextBoxFor(a => a.PatientDOB, "{0:yyyy-MM-dd}", new {@class = "bg-empty txtline input-s-sm", Value = @dob})
    </div>
</div>

Note: I am using jquery datepicker for this fields jquery code

<script type="text/javascript">
    $(document).ready(function () {
        $('#PatientDOB').datepicker({
            dateFormat: "yy-mm-dd",
            showStatus: true,
            showWeeks: true,
            currentText: 'Now',
            autoSize: true,
            gotoCurrent: true,
            showAnim: 'blind',
            highlightWeek: true
        });
    });
</script>

Earlier it was working fine have changed nothing in code but now showing this validation problem.I have tried solution given here solution tried.But none solved my problem. stackoverflow-question

That's really old problem. The ultimate solution for it - use Globalize.js library and change jquery validation methods with globalize methods:

$(document).ready(function () {
    Globalize.culture("pl-PL"); //Not sure that it's your locale, maby you need other
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || Globalize.parseDate(value);
    };
});

You should init this script after jquery validation load.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM