I'm trying to validate StartDate and EndDate using System.ComponentModel.DataAnnotations, such that the End Date must not be lesser than the Start Date. In my Model, I have defined the dates as follows:
public partial class MyModel
{
[Required]
public DateTime StartDate { get; set; }
[Required]
public DateTime EndDate { get; set; }
}
And I have also created a View Model as follows:
public class CompareDateVM : IValidatableObject
{
public MyModel myModel { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (myModel.EndDate < myModel.StartDate) {
yield return
new ValidationResult(errorMessage: "End Date cannot be lesser than Start Date.",
memberNames: new[] { "EndDate" });
}
}
}
The server-side validation works and the error message is able to display in my View Page's `@Html.ValidationSummary(), but I am unable to get the validation working on the client-side.
@model CompareDateVM
<form asp-controller="AddDate" asp-action="Add" method="post">
<label class="label">Start Date</label>
<input type="date" asp-for="myModel.StartDate" />
<span asp-validation-for="myModel.StartDate" class="validation"></span><br /><br />
<label class="label">End Date</label>
<input type="date" asp-for="myModel.EndDate" />
<!-- This is where the client side validation error message show up, but it does not appear-->
<span asp-validation-for="myModel.EndDate" class="validation"></span>
<input type="submit" value="Add Date" />
</form>
<!-- Server side validation works -->
<p>@Html.ValidationSummary()</p>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js"></script>
How do I get <span asp-validation-for="myModel.StartDate" class="validation"></span> to show the error message on client side with jQuery Unobtrusive Validation?
IValidatableObjectdoes not give client side validation. For that you need aValidationAttributethat iplmementsIClientModelValidator(refer Model validation in ASP.NET Core MVC