How to trigger ASP.NET Core client-side validation from JavaScript
Asked Answered
V

2

10

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.

Valorize answered 29/9, 2020 at 21:2 Comment(0)
M
12

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; }
}
Mir answered 29/9, 2020 at 21:23 Comment(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().Valorize
Strange. I moved the reference to _ValidationScriptsPartial above the other JavaScript like you have it, but still no errors are displayed.Valorize
Yeah, I just tried a single level field and got the same result.Valorize
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())?Valorize
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.Valorize
It seems to be working now. I was running a lot of the test JavaScript in the browser so maybe something was skewed with that. But running it in response to the submit button seems to work fine. Thanks.Valorize
Js validation worked without the need for @section Scripts, I just used <script type="text/javascript"> and validate() works.Sambar
where is _ValidationScriptsPartial ? It is not in my .NET 6 MVC projectCementation
S
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"/>
    }
}
Sirenasirenic answered 28/10, 2022 at 17:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.