9

Is there an easy way with parsleyjs to make a field required depending on another field?

See my js fiddle here http://jsfiddle.net/marksteggles/wbhLq0t4/1/

<form data-parsley-validate="true">
    <div class="form-group">
        <label>
            <input name="request_signature" type="checkbox" />Require signature</label>
        <div class="request_signature_fields">
            <textarea class="form-control required" name="signature_reason" rows="3"></textarea>
        </div>
    </div>
    <input class="btn btn-success" name="commit" type="submit" value="Send" />
</form>

7 Answers 7

17

Minimally as of 2.2.0 you can create a custom validator:

window.Parsley.addValidator("requiredIf", {
   validateString : function(value, requirement) {
      if (jQuery(requirement).val()){
         return !!value;
      } 

      return true;
   },
   priority: 33
})

This gets applied in such a way:

<textarea 
   class="form-control required" 
   name="signature_reason" 
   rows="3"
   data-parsley-validate-if-empty="true"
   data-parsley-required-if="#my-field-to-check"
></textarea>

Explanation

data-parsley-required-if is the custom validator we just defined. It takes any arbitrary jQuery selector and if that field contains a non-falsy value it ensures that this field is not empty.

data-parsley-validate-if-empty is needed to ensure that the field is being validated at all, because Parsley does not validate empty non-required fields by default.

More data on custom validators here: http://parsleyjs.org/doc/index.html#custom

1
  • 1
    Thanks, beware though - this solution does not work well, if #my-field-to-check is a checkbox! If (jQuery(requirement).attr('type') === 'checkbox'), you need to check requirement value like this: var requirementValue = requirementInput.is(':checked'); Explanation: ".val()" on a checkbox always returns checkboxes value, regardless of whether it is checked or not. Commented Feb 27, 2022 at 17:54
10

There is no easy way yet (see this and this).

You can either toggle the attribute required with Javascript, or listen to the right parsley events on one field and check the other field.

1
  • Thank you. I ended up toggling the class required and then also using parsley().reset() in case the field had already been validated but the user had unchecked the checkbox. Commented Feb 13, 2015 at 12:22
5

Just incase anyone else is trying to work this out. The best way does seem to be altering the required attribute then clearing the values.

I used this:

HTML:

<input id="checkbox-id" type="checkbox">
<div id="conditional-inputs" style="display:none;">
  <input type="text" name="somename" />
  <input type="text" name="othername" />
  <input type="text" name="onemoreforluck" />
</div>

jQuery:

$("#checkbox-id").change(function() {
  if(this.checked) {
    $('#conditional-inputs').slideDown();
    /* use .slideDown to display conditional input block */
    $("#conditional-inputs :input").prop('required', true);
    /* set required attribute on all inputs inside conditional area */
  }
  else{
    $('#conditional-inputs').slideUp();
    /* use .slideUp to hide conditional input block */
    $("#conditional-inputs :input").prop('required', false).val('');
    /* remove required attribute on all inputs and empty values of inputs */
  }
})
2

I realise that this question was asked and answered in 2012, and is most likely related to the ParsleyJS v1, while the most recent version at the time of writing this is v2.2.0. However I had to do some work on an old form that used v1 and I found that conditionals are possible (with a little bit of jQuery). So here's to anyone who might still need this.

You can dynamically add and remove form elements and constraints (read: validation rules) using the following:

$('#form').parsley('addItem', '#input_id');
$('#form').parsley('removeItem', '#input_id');
$('#input_id').parsley('addConstraint', '{ required: true }');
$('#input_id').parsley('removeConstraint', 'required');

So using jQuery listeneners for when the checkbox changes we can execute this kind of code which will add the signature field as a required field. Here it is in action for the question.

< script src = "js/parsley-v1.js" > < /script>
<script>
$('#request_signature').on('click', function() {
  if($(this).is(':selected')) {
    $('#signature_form').parsley('addItem', '#signature_reason');
    $('#signature_reason').parsley('addConstraint', { required: true });
  } else {
    $('#signature_reason').parsley('removeConstraint', 'required' });
    $('#signature_form').parsley('removeItem', '#signature_reason');
  }
});
</script >
<form id="signature_form" data-parsley-validate="true">
  <div class="form-group">
    <label>
      <input id="request_signature" name="request_signature" type="checkbox" />Require signature</label>
    <div class="request_signature_fields">
      <textarea id="signature_reason" class="form-control" name="signature_reason" rows="3"></textarea>
    </div>
  </div>
  <input class="btn btn-success" name="commit" type="submit" value="Send" />
</form>

2

You can also hide the parts that are not required anymore, or disable the fields that are not needed, and add [disabled] and :hidden to the excluded Parsley option.

{
  excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden], [disabled], :hidden',
}

NB: you don't need to hide each field, hiding a parent div is enough.

I found a good example that I forked here ➡️ http://jsfiddle.net/capripot/xoaLs4bt/

1

This should be possible with the great little Parsley addon plugin found here: http://themonk.github.io/parsely-conditions/

0

I found the shortest method -

$('input[type=radio][name=nlcsu]').change(function() {  
// I am checking for a Radio button    
    if (this.value == 1) {
        $("#nlcsu_post").attr('required', '1');
        $("#nlcsu_year").attr('required', '1');
    } else if (this.value == 0) { 
       $("#nlcsu_post").removeAttr('required');
       $("#nlcsu_year").removeAttr('required');
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.