Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger ASP .NET Core MVC client-side validation without submitting

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.

like image 390
jayzcos Avatar asked Oct 28 '25 04:10

jayzcos


1 Answers

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.

like image 145
John H Avatar answered Oct 30 '25 22:10

John H