parsley js - conditional required if checkbox checked

老子叫甜甜 提交于 2019-12-05 05:46:21

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.

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

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 */
  }
})

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>

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/

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

Given that everyone and their mother's are using front-end JS frameworks these days, I figured I'd toss in the approach I normally use. In my case (knockout js), I'll use the framework to add/remove those certain fields based on the value bound to the checkbox.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!