ASP.NET Core: jquery.validate.js is not working when used with another <script> tag

4.2k views Asked by At

Using VS2017, I've created an ASP.NET MVC Core 1.1.1 app by using a default ASP.NET Core Web Application template with Individual User Account mode. As we know VS2017 creates and configures all necessary css and javascripts files inside the project by default. The validation is working fine on both client side and server side accept when I use an javascript along with jquery.validate.js as shown below:

Observations

  1. When I enter a correct value (of type float) in input box, the form submits successfully and the value gets inserted into the SQL db. But intentionally if I enter a string, say, abc the client-side error does not occur but on post action, as expected, ModelStat.IsValid returns false and hence the data does not get inserted into the db.
  2. On the source view (shown below) of the page (or using F12), I can see the jquery.validate.js is loaded correctly
  3. I've tried loading jquery.validate.js before <script>...<\script> and then moving it to after <script>...<\script> but jquery.validate.js loads successfully yet client-side validation still does not work.

View

@model MyProj.Models.MainViewModel
 ...
<div class="form-group">
 <label asp-for="Price"></label>
 <div class="col-md-10">
    <input asp-for="Price" class="form-control"></input>
    <span asp-validation-for="Price" class="text-danger"></span>
 </div>
 </div>
 <div>
   <button type="submit" name="submit"...>GO</button>
 </div>

@section scripts
{  
   @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
   <script>
     $(document).ready(function () {
     ...
     ...
     });
   </script>
}

Page Source View

...
<div class="col-sm-2">
    <small class="input-group-addon">$</small>
    <input class="form-control text-right" type="text" data-val="true" data-val-number="The field Price must be a number." id="Price" name="Price" value="">
    <span class="text-danger field-validation-valid" data-valmsg-for="Price" data-valmsg-replace="true"></span>
</div>
...
</div>
...
       <script src="/lib/jquery/dist/jquery.js"></script>
       <script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
       <script src="/js/site.js?v=EWaMeWsJBYWmL2g_KkgXZQ5nPe-a3Ichp0LEgzXczKo"></script>


    <script src="/lib/jquery-validation/dist/jquery.validate.js"></script>
    <script src="/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>


  <script>
    $(document).ready(function () {
    ...
    ...
   });
 </script>
1

There are 1 answers

0
Hatef. On

Its too late but hope this help you

use unobtrusive too like this :

@section scripts{
    <script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
}