9
votes

I'm using Yup to validate my Formik form, but I have no idea how to validate a radio input in Yup/Formik.

3

3 Answers

5
votes

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

1
votes

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.

0
votes

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