Parsley

Parsley Validator Demo

<< Back to examplesTry it on

Correctly fill at least one of these blocks


This example uses a trick. It uses a <div> tag like if it was an input. That input uses a custom validator that succeeds only if one of the groups (here "block-1" and "block-2") validate with the force option set.

Note that the <div> contains the fields in question. This way, events like change or input generated when the user fills in these fields will bubble up to the div and revalidate the custom field.

<h4>Correctly fill at least one of these blocks</h4>
<form class="demo-form">
  <div data-parsley-check-children="2" data-parsley-validate-if-empty="">
    <div class="first">
      <label for="firstname">Firstname:</label>
      <input type="text" class="form-control" name="firstname" data-parsley-length="[4, 20]" data-parsley-group="block-1">

      <label for="lastname">Lastname:</label>
      <input type="text" class="form-control" name="lastname" data-parsley-length="[4, 20]" data-parsley-group="block-1">
    </div>

    <hr>

    <div class="second">
      <label for="fullname">Fullname:</label>
      <input type="text" class="form-control" name="fullname" data-parsley-length="[8, 40]" data-parsley-group="block-2">
    </div>
  </div>
  <input type="submit" class="btn btn-default validate">
</form>

<script type="text/javascript">
$(function () {
  Parsley.addValidator('checkChildren', {
    messages: {en: 'You must correctly fill at least one of these blocks!'},
    requirementType: 'integer',
    validate: function(_value, requirement, instance) {
      for(var i = 1; i <= requirement; i++)
        if (instance.parent.isValid({group: 'block-' + i, force: true}))
          return true; // One section is filled, this check is valid
      return false; // No section is filled, this validation fails
    }
  });

  Parsley.on('form:submit', function() {
    alert("The form would be submitted at this point. " +
      "For this demo, we interrupt the processing.");
    return false; // Don't submit for this demo
  });

  $('.demo-form').parsley({
    inputs: Parsley.options.inputs + ',[data-parsley-check-children]'
  });
});
</script>