I am typing a DOB
- 22/12/1986
into my text box and the validation keeps firing. It says:
The field DOB must be a date.
My MODEL:
[System.ComponentModel.DisplayName("DOB")]
[DisplayFormat(DataFormatString = "@{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "Date Of Birth is required")]
[RegularExpression(@"{0:dd/MM/yyyy}", ErrorMessage = "Invalid Date")] // below is a link
public DateTime DOB { get; set; }
My VIEW:
<div class="form-group">
@Html.LabelFor(model => model.DOB, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.DOB, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.DOB, "", new { @class = "text-danger" })
</div>
</div>
In MS SQL database
the field is: DateTime
Why does my validation say that the date i type in is invalid?
The reason for the client side validation is that the
jquery.validate.js
plugin used byjquery.validate.unobtrusive.js
validates dates based onMM/dd/yyyy
format and your entering dates based on add/MM/yyyy
format.The specific code used in
jquery.validate.js
for validation iswhich depending on the browser your using will give different results (in Chrome,
new Date('22/12/1986')
returnsInvalid Date
but in FireFox it returns1987-10-11T13:30:00.000Z
which is valid, just not the date you entered)You need to override the
$.validator
to format dates in your culture. One option is to use the jquery.globalize plugin.Alternatively you can write your own script. Note that the following script is taken from my own plugin used in conjunction with a
@Html.DatePickerFor()
extension method that generates a datepicker. The extension method adds html attributes for the date format based on the server culture and is read with thevar format = regex.exec(this.inputFormat);
line of code that I have commented out and replaced with your hard coded format. If you only ever want thedd/MM/yyyy
format, then the script can be simplified because you only need the 'little-endian' formatSide note: Your
[RegularExpression]
attribute does nothing and can be removed.Replace
.
with/
at both the places as Ganesh mentioned -DisplayFormat
attribute ANDRegularExpression
attribute.