How do you trigger client-side validation in ASP .NET Core MVC without submitting a form?
I am using modals, and need to trigger validation (without submitting the form).
In jQuery, I could do this
$('#formID').validate().form()
However, I would like to trigger the unobtrusive validation included in ASP .NET Core.
Unobtrusive validation still exists with ASP.NET Core, you just have to include the relevant scripts. Here's a full example.
Assuming this model:
public class SomeViewModel
{
    [Required]
    public string Name { get; set; }
}
And this controller action:
public IActionResult Index()
{
    return View(new SomeViewModel());
}
And finally, the view:
@model SomeViewModel
@{
    ViewData["Title"] = "Home Page";
}
<form asp-action="Index" id="formID" method="post">
    <input asp-for="Name" />
    <span asp-validation-for="Name"></span>
    <input type="submit" />
</form>
@section Scripts {
    @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
    <script type="text/javascript">
        $(function () {
            // Silly example to demonstrate.
            $('#formID').validate().form();
            if ($('#formID').valid() === false) {
                console.log("invalid");
            } else {
                console.log("valid!");
            }
        });
    </script>
}
If you take a look inside ~/Views/Shared/_ValidationScriptsPartial.cshtml, you'll see it contains:
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
If you look in your developer tools console, it should validate the form immediately as the page is loaded, and display the required field is missing validation message next to the Name textbox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With