ASP.Net Core Client Side Validation not working

Viewed 352

I am using ASP.Net Core 5.0. I am trying to get my client side validation to work so that when you tab out of a required field, if the field is blank and required, the error message appears.

In my model I have -

[Required(ErrorMessage = "Please enter in the name.")]
[MaxLength(100, ErrorMessage = "The maximum length for the name is 100 characters.")]
public string Name { get; set; }

I have a partial view _ValidationScriptsPartial.cshtml which contains -

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

In my view I have -

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

Also in the view I have the field -

<div class="form-row">
   <div class="col-md-7">
      <div class="row">
         <label asp-for="Name" class="control-label col-md-3">Name</label>

         <div class="col-md-8 mb-2">
            <input asp-for="Name" class="form-control" maxlength="100" />
            <span asp-validation-for="Name" class="text-danger"></span>
         </div>
      </div>
   </div>
</div>

When the code is run the html is -

<div class="col-md-8 mb-2">
   <input class="form-control" maxlength="100" type="text" data-val="true" data-val-maxlength="The maximum length for the name is 100 characters." data-val-maxlength-max="100" data-val-required="Please enter in the name." id="Name" name="Name" value="The Name">
   <span class="text-danger field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
</div>

When I clear the field and I tab out, nothing happens! I have noticed that the value attribute of the field in HTML is not cleared. Is that the problem and if so, why is not clearing?

Am I missing anything?

Thanks

0 Answers
Related