I have this fluent validation rule:
public EmployeeAbsenceValidator() {
RuleFor(a => a.DateTo)
.GreaterThanOrEqualTo(a => a.DateFrom)
.WithMessage("The end date cannot be before the start date.");
}
In the Create POST-method in the controller, I'm validating the dates and saving to the database and redirecting to a details view for the employee if the dates are valid, or returning to the create-absence-view if they are not:
if (ModelState.IsValid)
{
EmployeeAbsenceValidator validator = new EmployeeAbsenceValidator();
ValidationResult result = validator.Validate(employeeAbsence);
if (result.IsValid)
{
_context.Add(employeeAbsence);
await _context.SaveChangesAsync();
return RedirectToAction("Details", "Employees");
}
else
{
result.AddToModelState(ModelState, null); // Passing error message to model state
return View(employeeAbsence);
}
}
This is the create-absence-view:
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="row">
<div class="form-group col-md-4">
<label asp-for="Percentage" class="control-label"></label>
<input asp-for="Percentage" class="form-control" />
<span asp-validation-for="Percentage" class="text-danger"></span>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label asp-for="DateFrom" class="control-label"></label>
<input asp-for="DateFrom" class="form-control" />
<span asp-validation-for="DateFrom" class="text-danger"></span>
</div>
<div class="form-group col-md-6">
<label asp-for="DateTo" class="control-label"></label>
<input asp-for="DateTo" class="form-control" />
<span asp-validation-for="DateTo" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<button type="submit" value="Save">Save</button>
</div>
</form>
If Percentage
is filled in correctly, and the DateTo
is prior to DateFrom
, the error message from fluent validation is shown on the date. But if the Percentage
is not valid, only the client side error message on Percentage
is shown. I guess that's because the server does'nt know about the invalidity of the dates, seeing as the form hasn't been submitted yet. How can I get both error messages? (Please tell me I don't need to write any JQuery...)