parsley js - conditional required if checkbox checked
Asked Answered
A

7

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>
Amarillo answered 12/2, 2015 at 11:36 Comment(0)
T
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.

Trichinize answered 12/2, 2015 at 15:5 Comment(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.Amarillo
K
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

Kalpak answered 6/4, 2016 at 22:51 Comment(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.Risarise
T
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.

Trichinize answered 12/2, 2015 at 15:5 Comment(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.Amarillo
F
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 */
  }
})
Fsh answered 23/9, 2016 at 20:44 Comment(0)
C
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>
Cimbri answered 19/1, 2016 at 11:34 Comment(0)
I
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/

Insensitive answered 29/12, 2016 at 17:29 Comment(0)
C
1

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

Coverdale answered 27/8, 2015 at 23:44 Comment(0)
Q
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');
    }
});
Quenelle answered 12/8, 2022 at 4:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.