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

mc 4,876 Reputation points
2022-08-23T09:31:07.01+00:00

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

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

Accepted answer
  1. AgaveJoe 28,876 Reputation points
    2022-08-23T11:01:34.197+00:00

    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.

    234073-capture.png

    Code

    @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 (SqlWork.com) 68,311 Reputation points
    2022-08-23T16:02:14.04+00:00

    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.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.