Validate Checkbox or Radio Button

Validate checkboxes & radio buttons, Ensure user choices in your forms!.

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.

Understanding Checkbox and Radio Button Validation:

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.

Built-in Validators.requiredTrue() for Checkboxes:

For checkboxes, the built-in Validators.requiredTrue() from @nattyjs/tidy is ideal. This validator ensures at least one checkbox in the group is selected.

Implementing Validation:

1. Checkbox Validation with Validators.requiredTrue():

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()],
  },
});

2. Integrate the Form Input (Checkbox Example):

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>

Complete Code Walkthrough

<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>