heavywar
heavywar

Reputation: 149

jQuery Validate .valid() function doesn't work

If I do this:

$('#form').validate({
    // ....
})

And then I hide the form #form:

$('#form').hide() .

Then I check $('#form').valid(), I always get true even if the form should be invalid.

Example: Click checkTestValid with nothing in the text field when the form is showing (it alerts false), then use clickHide to hide the form, and then use checkTestValid to check again (it alerts true):

$('#testForm').validate({
  rules: {
    testInput: {
      required: true,
    }
  },
});

$(".btnTest").click(function() {
  $("#tab2").hide();
})
$(".btnTest2").click(function() {
  $("#tab2").show();
})
$(".clickTestVelid").click(function() {
  alert($("#testForm").valid())
})
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.js"></script>

<div id="tab1">
  <button class="btnTest">clickHide</button>
  <button class="btnTest2">clickShow</button>
</div>
<div id="tab2">
  <form id="testForm">
    <input required value="" name="testInput">
  </form>
</div>

<button class="clickTestVelid">clickTestValid</button>

Upvotes: 0

Views: 209

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115202

By default, it ignores hidden elements since the default value of ignore option is ":hidden" so update the ignore option.

$('#testForm').validate({
  // updated to ignore class selector to ignore only elements with class .ignore
  ignore: ".ignore"
  rules: {
    testInput: {
      required: true,
    }
  },
});

Upvotes: 4

Related Questions