I'm using Yup to validate my Formik form, but I have no idea how to validate a radio input in Yup/Formik.
Formik supports field-level validation via the validate prop of <Field> / <FastField> components or useField hook. This function can be synchronous or asynchronous (return a Promise). It will run after any onChange and onBlur by default.
import React from 'react'; import { Field } from 'formik'; const RadioButton = (props) => { const { label, name, options, ... rest } = props; return ( <div> <label htmlFor={name}>{label}</label> <Field name={name} {... rest} > { ({ field }) => { return options. map(option => { return ( <React.
Solution: const yup = require('yup') const { setLocale } = yup setLocale({ mixed: { notType: 'the ${path} is obligatory', required: 'the field ${path} is obligatory', oneOf: 'the field ${path} must have one of the following values: ${values}' } }) const myNameSchema = yup. object(). shape({ first_name: yup.
You validate the radio group. The only validation failure that is possible, is if you don't have a default button selected, and the user doesn't select any of the radio buttons.
Given:
<RadioButtonGroup
id="radioGroup"
label="One of these please"
value={values.radioGroup}
error={errors.radioGroup}
touched={touched.radioGroup}
>
<Field
component={RadioButton}
name="radioGroup"
id="radioOption1"
label="Choose this option"
/>
<Field
component={RadioButton}
name="radioGroup"
id="radioOption2"
label="Or choose this one"
/>
</RadioButtonGroup>
Validation code:
radioGroup: Yup.string().required("A radio option is required")
As used in context:
<Formik
...
validationSchema={Yup.object().shape({
radioGroup: Yup.string().required("A radio option is required"),
...
})}
Copied from this larger validation example:
https://gist.github.com/mrtony/c1ba5f8ec4122d2866b292fc36152d34
your radioInputGroup values:
state = {
gender: [
{
id: 0,
type: "woman",
text: interpreter("ImFemale")
}, {
id: 1,
type: "man",
text: interpreter("ImMale")
}
]
}
and your yup validationSchema:
ValidationSchema = Yup.object().shape({
gender: Yup.boolean().required().oneOf([0 , 1]),
});
note: you should to use gender values in .onOf() function.
if you want to show some msg for error message, use this code for yup validationSchema:
ValidationSchema = Yup.object().shape({
gender: Yup.boolean().required().oneOf([0 , 1], 'Selecting the gender field is required'),
});
Theoretically it shouldn't be different from any other value. You're tracking the radio value (or Formik's tracking it for you) somewhere in your state as a string most likely, and you simply need to apply the rules to the value that you're storing.
If you want to make sure the value matches only the presented radio options, you can use oneOf to accomplish that, but otherwise it's no different than any other scalar value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With