Lutaaya Huzaifah Idris
Lutaaya Huzaifah Idris

Reputation: 3990

Validation accept only two specific fields the selector with yup

Whats the best way to allow only two specified values in the selector, for example I have 2 fields for a user to select :

  1. US

  2. UGX

below is my code snippet :

Validations code :

const signUpSchema = Yup.object().shape({
    countrySelector: Yup.string().required('Please select the country'),
    
});

JSX snippet

<Formik
                        validationSchema={signUpSchema}
                        onSubmit={handleSignUpAsync}
                        initialValues={{
                            countrySelector: '',
            
                        }}
                    >
                        <Form>
                            <Field
                                as="select"
                                className="browser-default custom-select"
                                name='countrySelector'>
                                <option value="-">-</option>
                                <option value="DE">DE</option>
                                <option value="US">US</option>
                            </Field>
                        </Form>
                    </Formik>

Upvotes: 7

Views: 4445

Answers (1)

thedude
thedude

Reputation: 9812

Use the oneOf validator from yup

mixed.oneOf(arrayOfValues: Array, message?: string | function): Schema

e.g.

const signUpSchema = Yup.object().shape({
    countrySelector: Yup.string().oneOf(['US', 'UGX']).required('Please select the country'),
});

Upvotes: 13

Related Questions