【问题标题】:Validation accept only two specific fields the selector with yup验证只接受选择器的两个特定字段 yup
【发布时间】:2021-12-08 04:52:55
【问题描述】:

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

  1. 美国

  2. UGX

下面是我的代码 sn-p :

验证码:

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

JSX sn-p

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

【问题讨论】:

    标签: javascript reactjs yup


    【解决方案1】:

    使用来自yuponeOf 验证器

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

    例如

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

    【讨论】:

      猜你喜欢
      • 2017-07-10
      • 2019-09-29
      • 1970-01-01
      • 2019-01-06
      • 2021-11-01
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多