Search code examples
jqueryunobtrusive-validationeonasdan-datetimepicker

JQuery DateTimePicker not validating using Unobtrusive Validation


Using this Jquery DateTimePicker. I want to be sure that the TimeStamp is entered on Submit so in my ViewModel it is a Required field, however, due to how the control is styled, the ID that is Required in the ViewModel is not set on the Input Control, rather the surrounding Div and so the control does not Validate.

Any ides on how to fix this issue

ViewModel

[Required(ErrorMessage = "RequiredField")]
[Display(Name = "TimeStamp")]
public DateTime TimeStamp { get; set; }

HTML

<div class="form-group">
    <label asp-for="TimeStamp" class="control-label"></label>
    <div class="input-group date" id="TimeStamp">
        <input type="text" class="form-control" />
        <span class="input-group-addon">
            <span class="glyphicon glyphicon-calendar"></span>
        </span>
    </div>
    <span asp-validation-for="TimeStamp" class="text-danger"></span>
</div>

Working Code

<div class="form-group">
    <label asp-for="TimeStamp" class="control-label"></label>
    <div class="input-group date" id='TimeStampCal'>
        @Html.TextBox("TimeStamp", null, new { @class = "form-control" })
        <span class="input-group-addon">
            <span class="glyphicon glyphicon-calendar"></span>
        </span>
    </div>
    <span asp-validation-for="TimeStamp" class="text-danger"></span>
</div>

JS

$('#TimeStampCal').datetimepicker();

Solution

  • I got it working by giving the Div a different name from my model, just to initialize it and instead of using TagHelpers, if I use MVC controls, it works as a datetimepicker and it validates on Submit.

    See code above