验证仅接受选择器的两个特定字段,是的

Validation accept only two specific fields the selector with yup

在 select 中只允许两个指定值的最佳方法是什么,或者,例如我有 2 个字段供用户 select :

  1. 美国

  2. UGX

下面是我的代码片段:

验证码:

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

JSX 片段

<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>

使用来自 yup

oneOf 验证器

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

例如

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