admin管理员组

文章数量:1287526

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>

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>
Share Improve this question edited Oct 21, 2021 at 12:20 Lutaaya Huzaifah Idris asked Oct 21, 2021 at 12:08 Lutaaya Huzaifah IdrisLutaaya Huzaifah Idris 4,0109 gold badges43 silver badges86 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

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

本文标签: javascriptValidation accept only two specific fields the selector with yupStack Overflow