11

Is there any way to trigger ASP.NET Core client-side validation from JavaScript?

I have a Razor Pages page with a <form> that includes content like this:

<div class="row"> <div class="col-md-6"> <label asp-for="LocationModel.Location" class="control-label"></label> <input asp-for="LocationModel.Location" class="form-control" /> <span asp-validation-for="LocationModel.Location" class="text-danger"></span> </div> <div class="col-md-6"> <label asp-for="LocationModel.LoadsPerMonth" class="control-label"></label> <input asp-for="LocationModel.LoadsPerMonth" class="form-control" /> <span asp-validation-for="LocationModel.LoadsPerMonth" class="text-danger"></span> </div> </div> 

If I submit the form, any validation errors are highlighted and displayed. Is there any way to trigger this from JavaScript?

I'm not actually submitting the form to the server. I just want to use the values in JavaScript. But I'd like to use ASP.NET Core validation, if I can. I can see that I can just set the text of the validation <span>s. Maybe I could do that if I knew how to make the control border red the way the validation does.

I found a number of examples that do this, but not for ASP.NET Core or Razor Pages.

    3 Answers 3

    13

    You can do this with unobtrusive validation. To do that, you need to include the partial view that renders the jQuery unobtrusive validation scripts. To do that, add the following to the bottom of your view:

    @section Scripts { // You can find the partial in ~/Views/Shared @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } } 

    Next up, as a silly example to validate the form from JavaScript on load, you can add a script to that same Scripts section, underneath the inclusion of the partial:

    @section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } <script type="text/javascript"> $(function () { $('#formID').validate(); if ($('#formID').valid() === true) { console.log("valid"); } else { console.log("invalid"); } }); </script> } 

    Update per comments

    @model SiteViewModel <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 () { $('#formID').validate(); if ($('#formID').valid() === false) { console.log("invalid"); } else { console.log("valid!"); } }); </script> } 

    where SiteViewModel is just:

    public class SiteViewModel { [Required] public string Name { get; set; } } 
    8
    • I'm already including _ValidationScriptsPartial but something's missing. If I add a submit button and click it, all my validation boxes show errors. But this doesn't happen if I call $('#myform').validate().CommentedSep 29, 2020 at 21:37
    • Strange. I moved the reference to _ValidationScriptsPartial above the other JavaScript like you have it, but still no errors are displayed.CommentedSep 29, 2020 at 21:44
    • Yeah, I just tried a single level field and got the same result.CommentedSep 29, 2020 at 21:48
    • I have to step away. I appreciate your response so far. If it's working for you, it must be right. But something's wrong. Perhaps you could post the resulting markup (before calling validate())?CommentedSep 29, 2020 at 21:50
    • I wonder if it could have anything to do with the fact that you're using MVC and I'm using Razor Pages. Anyway, I'll dig deeper when I get back. That's why I wondered if your produced HTML could be different.CommentedSep 29, 2020 at 22:14
    1

    In the latest .Net Core applications, you will find _ValidationScriptsPartial.cshtml file inside Shared folder. Use it in the very end of your views (.cshtml) after all the tags closed for client side validation

    @section Scripts{ @{ <partial name="_ValidationScriptsPartial"/> } } 
      0

      SO has reached the state where most threads are either out-of-date or left incomplete.

      That said, and for the shake of completeness, you are right, it won't badge even though the original answer is correct (you have to include _ValidationScriptsPartial).

      The only way I've found it to be working properly is by calling submit() in the click event handler of a button (of type submit or otherwise):

      <input type="submit" click="submitForm" /> ... function submitForm() { if ($('#formID').valid()) { $('#formID').submit(); } else { return false; } } 

      That return false will effectively cause any validation errors to show up in their respective asp-validation-for<span>s.

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.