In one of my controller actions, the first thing I do is pass the model to a new action that essentially just parses input to determine whether or not the user entered a valid date. The model is then returned and ModelState.IsValid is inspected.
public Import ValidateUploadModel(Import Model)
{
// Do not allow future dates
if (Model.CurrMoInfo.CurrMo > DateTime.Now)
{
ModelState.AddModelError("FutureDate", "You cannot assign a future date.");
}
// Do not allow dates from the same month (we run the processing a month behind)
if (Model.CurrMoInfo.CurrMo.Month == DateTime.Now.Month)
{
ModelState.AddModelError("SameMonth", "You must process a previous month.");
}
// Ensure day is last day of a previous month
if (Model.CurrMoInfo.CurrMo.Day != DateTime.DaysInMonth(Model.CurrMoInfo.CurrMo.Year, Model.CurrMoInfo.CurrMo.Month))
{
ModelState.AddModelError("LastDay", "You must enter the last day of the month.");
}
// Do not allow dates older than 12 months back
if (Model.CurrMoInfo.CurrMo < DateTime.Now.AddMonths(-12))
{
ModelState.AddModelError("TooOld", "Date must not be older than a year.");
}
return Model;
}
At the point where I know I have model state errors, I am able to correctly show them in my razor view by putting the following
<span class="text-danger">@Html.ValidationSummary(false)</span>
So, since all of my model state errors are for the same input on the page I can safely do this. But what if I have various inputs with various errors that I need to display independently of one another? How would I go about doing this? Additionally, is there a better (or more appropriate) way to do this aside from using @Html.ValidationSummary?
I have searched through Microsoft docs and a few dozen StackOverflow questions to try and translate older answers into the .Net Core way of doing things with no luck.
Edit for clarity:
Here is the entire card in the razor view:
<div class="card-body">
@if (Model.StagingCount == 0)
{
<input asp-for="@Model.CurrMoInfo.CurrMo" type="date" required class="col-lg-12" />
}
else
{
<input asp-for="@Model.CurrMoInfo.CurrMo" type="date" disabled="disabled" required class="col-lg-12" />
}
<span class="text-danger">@Html.ValidationSummary(false)</span>
</div>
The input is for a model property however it is not annotated. I've written my own rules and manually add errors to the model state if the rules are not adhered to. The code I have works however it's not scalable when I start needing to validate more fields. I just want to know what a better way of doing this is.
<span asp-validation-for="FutureDate" class="text-danger"></span>
– Reederasp-validation-for
tag helpers on them. These will act as a place to display a specific error message when it's generated. see learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/… for more detail – Tomtomasp-validation-for
will not work here since the errors are specifically being added to the ModelState. – India