Skip to content
Advertisement

validate field after setting value via jQuery

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("some@email.com");

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("some@email.com"); 
$("#cartForm").validate();

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

enter image description here

Advertisement

Answer

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("user@company.com");

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

});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement