5
I have a model with a property like DateTime
:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[DataType(DataType.Date, ErrorMessage="Data em formato inválido")]
public DateTime? Date {get;set;}
And in the View
:
@Html.TextBoxFor(model => model.Date)
@Html.ValidationMessageFor(model => model.Date)
When typing a date with the following value: 11/11/1111, is the value not the format, and I send the POST, it passes ModelState
, but in the SaveChange
causes error:
The Conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.
What I’ve done so far and haven’t succeeded:
1 - In my Web.config
the following attribute:
<globalization uiCulture="pt-BR" culture="pt-BR" enableClientBasedCulture="true" requestEncoding="UTF-8" responseEncoding="UTF-8" fileEncoding="UTF-8" />
2 - Installation of the jQuery
globalize
and jQuery Validate
globalize
.
The loading order is this:
<script src="~/Scripts/libs/jquery.globalize/globalize.js"></script>
<script src="~/Scripts/libs/jquery.globalize/cultures/globalize.culture.pt-BR.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Content/Scripts/libs/jquery.validate/jquery.validate.globalize.min.js"></script>
3 - Treatment of number and dates using jQuery Validate
+ globalize
, with the following code:
jQuery.extend(jQuery.validator.methods, {
date: function (value, element) {
return this.optional(element) || /^\d\d?\/\d\d?\/\d\d\d?\d?$/.test(value);
},
number: function (value, element) {
return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);
}
});
How to validate this date entry or create a "range" on the client and not on the server?
As dumb as it is, I had a similar problem that was solved by switching from @Html.Textboxfor(model => model.Date) to @Html.Editorfor(model => model.Date)
– Rafael Barbosa
@Rafaelbarbosa so it is, but I use Textboxfor because of my datepicker plugin...using Editorfor does not work..
– Rod
By the way, he even opens my datepicker, but then also opens the Html5 and does not arrow the values with my datepicker, rs
– Rod
@Rafaelbarbosa actually kkk using the datepicker of Html5 itself worsens the situation, it does not even accept the format I pass, always speaking the field .. must be a date
– Rod
@Rod What is the value defined on the date before the
SaveChanges
?– Leonel Sanches da Silva
@Ciganomorrisonmendez in question has the value, which is 11/11/1111, I know it is a little improbable, but it is that there is always a user who wants to fill for test everything with 11 or single value 22...
– Rod