This page explores validating checkbox and radio button inputs. Ensuring proper selection in these input types is crucial for forms requiring user choices or confirmations.
Checkboxes and radio buttons allow users to select one or more options (checkboxes) or a single option (radio buttons) from a group. Validation helps ensure users make the necessary selections.
For checkboxes, the built-in Validators.requiredTrue() from @nattyjs/tidy is ideal. This validator ensures at least one checkbox in the group is selected.
Here's how to use Validators.requiredTrue() for checkbox validation:
import { useForm } from "@nattyjs/tidy";
const user = {
accept: '', // Initial state for the checkbox
};
const userForm = useForm(user, {
validators: {
accept: [Validators.requiredTrue()],
},
});
For checkboxes, use a checkbox element with binding:
<template>
<div>
<input type="checkbox" v-model="userForm.accept" /> I Agree
<span>{{ userForm.errorMessage.accept }}</span>
</div>
</template>
<script setup lang="ts">
import { useForm, Validators } from '@nattyjs/tidy';
import { reactive } from 'vue';
const user = {
accept:''
};
const userForm = reactive(useForm(user, {
validators: {
accept:[Validators.requiredTrue()]
},
}))
</script>
<template>
<div>
<input type="checkbox" v-model="userForm.accept"/> I Agree
<span>{{ userForm.errorMessage.accept }}</span>
</div>
</template>