- Published on
How to Validate Radio Inputs in Yup and Formik
- Authors
- Name
- Ripal & Zalak
How to Validate Radio Inputs in Yup and Formik
Validating radio input fields in Formik with Yup is straightforward once you understand how to handle radio groups. This guide provides examples and best practices to ensure your forms behave as expected.
The Problem
Radio inputs in Formik are typically grouped, with each option representing a specific value. The main challenge arises when validating whether a user has selected any option, ensuring no submission occurs without user input.
Solution
1. Formik and Yup Setup
Here’s a simple example of a form with a radio group for selecting gender.
import React from 'react'
import { Formik, Field, Form, ErrorMessage } from 'formik'
import * as Yup from 'yup'
const validationSchema = Yup.object({
gender: Yup.string().required('Please select a gender.'),
})
const RadioInputForm = () => {
return (
<Formik
initialValues={{ gender: '' }}
validationSchema={validationSchema}
onSubmit={(values) => {
alert(JSON.stringify(values, null, 2))
}}
>
{() => (
<Form>
<div>
<label>
<Field type="radio" name="gender" value="male" /> Male
</label>
<label>
<Field type="radio" name="gender" value="female" /> Female
</label>
<div style={{ color: 'red' }}>
<ErrorMessage name="gender" />
</div>
</div>
<button type="submit">Submit</button>
</Form>
)}
</Formik>
)
}
export default RadioInputForm
2. Validation Schema
In the example above, we use Yup’s required
method to ensure a value is selected from the radio group:
const validationSchema = Yup.object({
gender: Yup.string().required('Please select a gender.'),
})
oneOf
3. Adding Custom Validation with If you want to ensure the selected value is one of the predefined options, you can use Yup’s oneOf
method:
const validationSchema = Yup.object({
gender: Yup.string()
.required('Please select a gender.')
.oneOf(['male', 'female'], 'Invalid selection.'),
})
Common Issues and Fixes
Issue 1: Default Value Not Set
If no default value is set, users must select an option explicitly. To provide a default, modify the initialValues
in Formik:
initialValues={{ gender: "male" }}
Issue 2: Error Not Displayed Properly
Ensure ErrorMessage
is correctly configured to show validation errors:
<ErrorMessage name="gender" />
Issue 3: Validating Against Incorrect Values
Always validate radio values against the predefined options. Use oneOf
to avoid accepting unexpected values.
FAQs
Can I validate multiple radio groups in the same form?
Yes, you can validate multiple radio groups by adding corresponding fields to the validation schema:
const validationSchema = Yup.object({
gender: Yup.string().required('Please select a gender.'),
preference: Yup.string().required('Please select a preference.'),
})
How do I style validation errors?
Use custom CSS to style error messages:
<div className="error">
<ErrorMessage name="gender" />
</div>
.error {
color: red;
font-size: 0.875rem;
}