How to use jquery.validate.unobtrusive.js for validate the form?

mc 3,601 Reputation points

I am using .net core mvc and there is page of Index.cshtml and Edit.cshtml.

I want to add validation to Edit.cshtml

I import jquery.validate.js and jquery.validate.unobtrusive.js but it not work.

<input type="text" class="form-control" placeholder="Erorr required" autocomplete="off" asp-for="Number" /> <span asp-validation-for="Number"></span>

If the Number is null then the span will appear to inform the user

but nothing happen

A set of technologies in the .NET Framework for building web applications and XML web services.
4,115 questions
A set of technologies in the .NET Framework for building web applications and XML web services.
3,231 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,021 Reputation points

    Your question is rather confusing because the ASP.NET Core default templates come with unobtrusive validation. All you have to do is make a reference to the _ValidationScriptsPartial.cshtml partial. This is an option when you created the View.



    @section Scripts {  
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  

    Also, the official documentation covers this subject.

    Model validation in ASP.NET Core MVC and Razor Pages

1 additional answer

Sort by: Most helpful
  1. Bruce ( 54,621 Reputation points

    unobtrusive validation uses attributes to define the validation rules. at script load, it queries the attributes and add the rules to jquery. validate.

    to include an element in validation you need to define two attributes. first enable validation with data-val="true", and then define validation type with data-val-<rule>="<rule options">" the form also needs a data-val="true".

    <input type="text"  name="Number" data-val="true" data-val-required="true" />   
    <span class="field-validation-valid" data-valmsg-for="Number">Number is Required</span>  

    the tag helpers should render these based on model validation attributes. view source to see.

    2 people found this answer helpful.