I need to store in th SQL-Server DB a date format "29-12-2014" using datepicker but I get the message The field XXX must be a date.
My last try was Regular Expression:
Model #1:
[RegularExpression(@"([3][0,1]|[0-2]\d)-([1][0-2]|[0]\d)-(\d\d\d\d)", ErrorMessage = "Valor inválido.")]
public Nullable<DateTime> ETD { get; set; }
Model #2:
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
public Nullable<DateTime> ETD { get; set; }
View:
<div class="editor-field">
@Html.TextBoxFor(model => model.ETD)
@Html.ValidationMessageFor(model => model.ETD)
</div>
jQuery:
$(function () {
$("#ETD").datepicker();
});
I always get the message "The field ETD must be a date."
Any idea?
Thanks.
Its my understanding that the format 'dd-MM-yyyy' is the problem, here. The jquery unobtrusive validation is trying to instantiate a new Date(strVal) object, and it doesn't know what to do with the string '29-12-2014'.
See Unobtrusive validation in Chrome won't validate with dd/mm/yyyy
magritte answered that redefining the unobtrusive validator's date method, using the jQuery Globalize library, to parse with the desired format string should solve the issue:
$.validator.methods.date = function (value, element) {
return this.optional(element) || Globalize.parseDate(value, "dd-MM-yyyy", "en");
}
Update
I recreated your problem locally, and was able to replicate the 'required field validation not firing prior to form post' issue, when the Globalization library was not installed. Once I installed and loaded the library, the front-end worked as expected, with unobtrusive validation accepting the modified dd-MM-yyyy date.
The library can be installed using the NuGet package manager and the following package: http://www.nuget.org/packages/jquery-globalize/. Then you need to update your html to include the globalize.js script.
The back-end was another story, which is going to rely on your local machine's globalization profile. I am assuming you are running a non-en/us machine where this format might parse? My machine is english/us and does not natively parse the modified date format, however using the below command, I successfully got a valid datetime:
DateTime.ParseExact(Request.Form["ETD"], "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
This should work to set your format in the box:
$("#ETD").datepicker({
dateFormat : 'dd-mm-yy'
});
Is the validation message coming from jQuery or C#? See this answer with respect to the former: https://stackoverflow.com/a/19519745/1803682
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With