JSFiddle - React, Tailwind, and code Playground

by Marc-André Lafortune

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/parsley.js/2.0.5/parsley.js"></script>
<form data-parsley-validate>
    <fieldset>
       <legend>Choice</legend>
       <input type="radio" name="choice" value="Drinks" required data-parsley-error-message="Choose drinks or food"/>Drinks
       <input type="radio" name="choice" value="Food"/>Food
   </fieldset>
    
   <fieldset id="drinks">
       <legend>Drinks</legend>
       <input type="checkbox" name="drinks" data-parsley-mincheck="2" data-parsley-trigger="change" data-parsley-error-message="Choose min 2 drinks"  />Water
       <input type="checkbox" name="drinks"/>Pepsi
       <input type="checkbox" name="drinks"/>Orange Juice
   </fieldset>
    
   <fieldset id="food">
       <legend>Food</legend>
       <input type="checkbox" name="food" data-parsley-mincheck="2" data-parsley-trigger="change" data-parsley-error-message="Choose min 2 foods" />Cake
       <input type="checkbox" name="food"/>Hotdog
       <input type="checkbox" name="food"/>Pizza
   </fieldset>
       
   <button type="submit">submit</button>

</form>

<div class="note">
    <h2>Required behaviour</h2>
    <p>Only corresponding fields of selected choice are validated. E.g if food is selected drinks fields don't get validated.</p>
    <h2>What happens</h2>
    <p>If choice is selected <b>and</b> then changed after triggering validation, error remains and form can't be submitted/continued. E.g. if drinks is selected and an option chosen, then choice changed to food validation errors still occurr for the drinks fields.</p>
</div>

SCSS

fieldset {
    margin-bottom: 1em;
}

.parsley-errors-list {
	color: red;
}

.note {
    padding: 1em;
    margin-top: 2em;
    border-left: solid 1em #85B200;
    background: #EFFFBF;
}

JavaScript

var toggle = function($elem, require) {
    $elem.prop('required', require)
    if (require)
        $elem.attr('data-parsley-mincheck', '2');
    else
        $elem.removeAttr('data-parsley-mincheck');
}
var update = function() {
    var val = $("input[name=choice]:checked").val()
    $('#drinks').toggle(val == 'Drinks')
    toggle($("input[name=drinks]:first"), val == 'Drinks');
    $('#food').toggle(val == 'Food')
    toggle($("input[name=food]:first"), val == 'Food');
}
update()
$("input[name=choice]").on('click', update);