【问题标题】:How to chain on custom validations using Yup如何使用 Yup 链接自定义验证
【发布时间】:2020-11-05 08:43:32
【问题描述】:

我想将 .test() 方法添加到 validationSchema。测试是寻找常见的电子邮件域拼写错误。例如,检查 gmail 是否拼错了“gmial”或“gnail”。

const validationSchema = Yup.object({    
         email: Yup.string().lowercase()
        .email('You have entered an invalid email')
        .required('This field is required')
        .test('test-name', 'Did you mean @gmail??????', function(value){
            if (value.includes('gmial' || 'gnail'))
                return this.createError('')
    })
<Formik>
      <Form>
        <div className='form-control'>
          <label htmlFor='email'>Email</label>
          <Field type='text' id='email' name='email' />
          <ErrorMessage name='email' component={TextError} />
        </div>
      </Form>
</Formik>

【问题讨论】:

    标签: reactjs formik yup


    【解决方案1】:

    在您的测试中返回一个布尔结果。

    const validationSchema = Yup.object({
      email: Yup.string()
        .lowercase()
        .email('You have entered an invalid email')
        .required('This field is required')
        .test('Gmail?', 'Did you mean @gmail?', (value) => value.includes('gmial' || 'gnail')),
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-25
      • 2020-02-05
      • 2020-05-22
      • 2023-02-08
      • 2021-12-20
      • 2020-05-27
      • 1970-01-01
      • 2019-07-23
      相关资源
      最近更新 更多