Question

I'm using parsley validation to validate a registration form. My problem is that I have an input which will only be enabled when the user checks a check box. So how to make parsley validate that input only when the check box is checked?

  <form name="form1"  method="POST" data-validate="parsley">
How did you hear about us? :
      <ul class="checklist">
        <li>
          <input name="Internet" id="Internet" value="Internet"  data-mincheck="1" data-group="mygroupp" type="checkbox">
          <label>Internet</label>
        </li>
        <li>
          <input name="Newspaper" id="Newspaper" value="Newspaper" type="checkbox" data-mincheck="1" data-group="mygroupp">
          <label>Newspaper</label>
        </li> <li>
          <input name="Others" id="Others" class="input_control" value="Others" type="checkbox"/ data-mincheck="1" data-group="mygroupp" onClick="enable_text(this.checked)">
          <label>Others, Please Specify:</label>
        </li>
      </ul>
      <p>
        <input type="text" name="Otherinput" id="Otherinput" class="quter-width align-right margin_top_5"  data-required="true"  disabled="disabled" >
      </p>

The validation for the checkboxs is working fine but I want to add validation for "otherinput" input field which will only be validated when the "Others" checkbox is checked Can anyone direct me please. Thanks in advance.

Était-ce utile?

La solution

I don't think Parsley.js provides this functionality out of the box. Instead, you can write it custom by registering an onchange event listener like so:

$('input#others').change(function() {
  if (this.checked) {
    $('#otherinput').attr('disabled', 'false');
  } else {
    $('#otherinput').attr('disabled', 'true');
  }
});

Note: this assumes lowercase ID names (i.e. 'otherinput' instead of 'Otherinput').

I haven't tested, but something like this should work in theory.

Autres conseils

Parsley rely on jQuery (>= 1.6) that would need to be called before including Parsley.

Then, you can either use parsley.js unminified file or parsley.min.js minified one. These files and other builds (Remote, Extras..) are available here.

Finally, add data-parsley-validate to each you want to be validated.

That would look pretty much like this:

<script src="jquery.js"></script>
<script src="parsley.min.js"></script>

<form data-parsley-validate>
...
</form>

It has isValid() method that returns you true if validations is/are met successfully, so you can check whether form has valid data or not.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top