colinaut / alpinejs-plugin-simple-validate

Simple Alpine form validation plugin
97 stars 4 forks source link

Group of checkboxes validation error #15

Closed likeabas closed 1 year ago

likeabas commented 1 year ago

When you're using the x-validation.group for checkboxes something goes wrong with the validation when multiple checkboxes are selected and one is unselected. In this case, it shows the error message, while there are some checkboxes of the group still selected.

My code:

            <form id="form" x-validate x-data="{ option: '' }" @submit="$validate.submit">
                <h5 class="font-bold block mb-2">Question 1/6</h5>
                <div class="h-1 w-full bg-white mb-10 rounded">
                    {{-- change the width in % to move the progress bar --}}
                    <div class="h-1 bg-primary rounded" style="width: 17%"></div>
                </div>
                <p class="block mt-8 mb-4 font-bold">Select answer</p>
                <div id="checktest" class="grid grid-cols-2 gap-1" data-error-msg="Select at least 1 answer">
                    <label><input type="checkbox" x-validate.group name="checktest">Dit is check 1</label>
                     <label><input type="checkbox"  x-validate.group name="checktest">Check 2</label>
                     <label><input type="checkbox"  x-validate.group name="checktest">Check 3</label>
                     <label><input type="checkbox"  x-validate.group name="checktest">Check 4</label>
                </div>

                <button type="submit" class="btn btn-arrow pt-0">Volgende vraag</button>

            </form>
colinaut commented 1 year ago

The plugin is designed to grab the values to see which are checked. Since your checkboxes do not have values it is breaking. I can possibly make an enhancement to the plugin that can mark which is checked without values but the simplest way to fix this is to add value="Check 1", value="Check 2", etc.. You'd likely need values anyways for form submission.

likeabas commented 1 year ago

Thanks for the quick response! That makes total sense that I need to add values. I didn’t do that yet because I was first creating and testing the front-end. Perhaps just mentioning in the readme that this is needed (as with the name field and the x-data attribute) should solve it for other developers