[SOLVED] validate field after setting value via jQuery

Issue

I have asp net MVC project. And I have form with few inputs in view. For client side validation I use two libraries:

jquery.validate.js and jquery.validate.unbrostive.js

For example I have field email:

<div class="form-group">
    @Html.LabelFor(m => m.Email, new { @class = "required" })
    @Html.TextBoxFor(m => m.Email, new { @class = "form-control", @autocomplete = "nope" })
    @Html.ValidationMessageFor(x => x.Email)
</div>

If I press "submit" button with empty field , it shows me an error "Email field required"

Ok. If after message has been shown I put value in field via jQuery, like this:

$("#Email").val("[email protected]");

The error message still shows unlike if I type text the error dissaperes. I tried to manualy trigger validation, but the error still shows:

$("#Email").val("[email protected]"); 
$("#cartForm").validate();

Strange thing that after updating value via jQuery the can be submited even error shows.

enter image description here

Solution

Use $('form').validate().form(); to manually trigger the validation to re-run.
Call this AFTER setting the input field to a valid value, like this:

$("#validInput").click(function () {

    $("#UserName").val("[email protected]");

    $('form').validate().form();

});

Answered By – Denys Wessels

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *