首页 > 解决方案 > 来自 Yup 的自定义验证的错误消息不会消失

问题描述

作为注册过程的一部分,我想使用来自以下的自定义验证来检查任何重复的电子邮件Yup

validationSchema={yup.object().shape({
    email: yup
        .string()
        .email()
        .test({
            name: 'duplicate-email-check',
            params: 'value',
            message: 'Duplicate email already exists',
            test: async (value) => {
                firebase
                    .auth()
                    .fetchSignInMethodsForEmail(value)
                    .then(result => {
                        if (result === "password") {
                            return false
                        } else {
                            return true
                        }
                    })
                    .catch(err => console.log(err))
            }
        })
        .required(),
})}

我正在使用fetchSignInMethodsForEmail来获取具有相同电子邮件的任何类型的帐户,如果存在,则会抛出验证错误消息。我在混合()。文本()模式之后建模,但问题是错误消息“重复的电子邮件已经存在”即使没有重复的电子邮件出现,它也不会消失。

标签: javascriptreactjsreact-nativeformikyup

解决方案


这部分代码不返回返回布尔值的 Promisetest

test: async (value) => { // Notice this, adding curly braces will require you to put a return statement
                firebase
                    .auth()
                    .fetchSignInMethodsForEmail(value)
                    .then(result => {
                        if (result === "password") {
                            return false
                        } else {
                            return true
                        }
                    })
                    .catch(err => console.log(err))
            }

您可以将代码更改为:

test: async (value) => { // Notice this, adding curly braces will require you to put a return statement
                return firebase // Notice I added the return statement
                    .auth()
                    .fetchSignInMethodsForEmail(value)
                    .then(result => {
                        if (result === "password") {
                            return false
                        } else {
                            return true
                        }
                    })
                    .catch(err => console.log(err))
            }

推荐阅读