使用Formik、Yup和Reaction进行异步验证

人气:276 发布:2023-01-03 标签: reactjs formik yup

问题描述

我想使用formik进行异步验证,并使用yup进行验证架构,但我找不到示例或演示。

推荐答案

const validationSchema = Yup.object().shape({
    username:
        Yup.string()
            .test('checkDuplUsername', 'same name exists', function (value) {
                return new Promise((resolve, reject) => {
                    kn.http({
                        url: `/v1/users/${value}`,
                        method: 'head',
                    }).then(() => {
                        // exists
                        resolve(false)
                    }).catch(() => {
                        // note exists
                        resolve(true)
                    })
                })
            })
})
YUP通过测试方法提供了异步处理。 (KN是我的AJAX承诺函数) 祝你有愉快的一天。

19