Using ASP.NET Core unobtrusive client-side validation, I want to display the validation summary when a field changes, not just on form submit.
The <div asp-validation-summary="All"></div>
element displays relevant error messages for each field when the form is submitted, but not when the fields are modified (and the modified state is invalid).
Here is my example code:
My model:
public class InviteNewUser
{
[DisplayName("Email Address")]
[Required(ErrorMessage = "Please provide the invitee's Email Address")]
[EmailAddress(ErrorMessage = "Please provide a valid email address")]
[StringLength(254, ErrorMessage = "Maximum email address length exceeded")]
public string EmailAddress { get; set; }
}
My form:
@model InviteNewUser
<form data-ajax="true"
data-ajax-url="@Url.Action("InviteNewUser","Account")"
data-ajax-method="POST"
data-ajax-success="success"
asp-antiforgery="true">
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend ">
<label class="input-group-text" asp-for="@Model.EmailAddress">Invitee's Email</label>
</div>
<input class="form-control" asp-for="@Model.EmailAddress" />
</div>
</div>
<div asp-validation-summary="All" class="text-danger"></div>
<button type="submit" class="btn btn-primary">Invite</button>
</form>
@section scripts {
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.js"></script>
<script>
function success() {
alert("Success!");
}
</script>
}
My controller:
[Authorize]
public class AccountController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> InviteNewUser(InviteNewUser viewModel)
{
if (!ModelState.IsValid)
{
return View("~/Views/MyForm.cshtml",viewModel);
}
return Ok();
}
}
So if a user types an invalid email (e.g. zero length, or invalid email format) it should show in the validation summary.