Reputation: 67
I have has an issue trying to get jquery validation to accept a uk formatted date for a while now, basically when I add @Scripts.Render("~/bundles/jqueryval") to my section, the validation does not recognise my date field as having a valid value.
I have followed this guide (http://www.ablogaboutcoding.com/2017/08/12/mvc-uk-date-issues/) to try to solve the problem but have ran into an issue that I am hoping someone can help with. This issue is when the ModelBinder tries to convert the uk value to the DateTime. Code below:
I have tried converting the value to a DateTime (see var date2) & this will work with uk dates but I cannot then apply the correct culture.
Model Binder:
public class NullableDateTimeModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null || string.IsNullOrWhiteSpace(value.AttemptedValue))
return null;
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
try
{
var date2 = Convert.ToDateTime(value.AttemptedValue);
var date = value.ConvertTo(typeof(DateTime), Thread.CurrentThread.CurrentUICulture);
return date;
}
catch (Exception ex)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);
return null;
}
}
}
Fails at var date. Inner Exception = "String was not recognized as a valid DateTime". Message = "20/05/2019 is not a valid value for DateTime".
If I enter a date of "10/05/2019", I do not get an exception as it can be converted to an American date.
Model:
[Required(ErrorMessage = "Enter the planned start date of the project")]
[DataType(DataType.Date)]
[Column(TypeName = "DATE")]
public DateTime? PlannedStartDate { get; set; }
View:
<div class="form-inline">
<div class='input-group date mydatepicker'>
@Html.TextBoxFor(m => m.FormData.PlannedStartDate, new { title = "Planned Start Date", @class = "form-control", placeholder = "dd/mm/yyyy" })
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
Scripts:
$(document).on('click', '#ajaxCreate2', function () {
var $form = $('#form0')
.validate({
rules: {
FormData_PlannedStartDate: {
dateITA: true
}
}
});
if ($form.valid()) {
$.ajax({
async: false,
type: 'POST',
url: 'ajaxCreate',
datatype: "json",
data:
JSON.stringify($('#form0').serialize()),
success: function (data) {
}
});
} else {
var validator = $('#form0').validate();
$.each(validator.errorMap, function (index, value) {
$(function () {
var a = value;
if (a != '')
toastr.error("", a);
})
});
}
});
Upvotes: 0
Views: 406
Reputation: 13060
You're going to have to be specific about your DateTime conversions and use a specific culture, instead of relying on the server default culture.
DateTime.Parse("20/05/2019", CultureInfo.GetCultureInfo("en-gb"))
This will correctly parse UK formatted (dd/MM/yyyy) dates.
Upvotes: 0