【问题标题】:How to check email id already exists or not using yup validation?如何使用 yup 验证检查电子邮件 ID 是否已存在?
【发布时间】:2021-10-10 09:42:12
【问题描述】:

我正在 React 应用程序中创建一个登录页面,我将电子邮件和密码提交给 api。现在我想知道输入的电子邮件是否已经存在或没有使用 yup 验证。

【问题讨论】:

    标签: reactjs validation yup


    【解决方案1】:

    是的,这是可能的,下面我将展示我是如何检查我的 MongoDB Atlas 的:

    checkEmail: Yup.boolean(),
    email: Yup.string()
      .email("Email should be valid and contain @")
      .required("Email is required")
      .when("checkEmail", {
        is: true,
        then: Yup.string()
        .test({
          message: () => "Email already exists",
          test: async (values) => {
            if (values) {
              try {
                let response = await fetch("http://localhost:3005/users/check", {
                  method: "POST",
                  headers: {
                    "Content-Type": "application/json",
                  },
                  body: JSON.stringify({ email: values }),
                });
                if (response.ok) {
                  return true;
                } else {
                  return false;
                }
              } catch (error) {
                console.log(error);
              }
            }
          },
        }),
        
      }),
    
    

    在我的回调 onBlur 中的字段电子邮件上,我手动设置了 checkEmail 的值,该值在我的初始值中为 false,如下所示:

                    onBlur={(e) => {
                          props.handleBlur(e);
                          if (!props.errors.email) {
                            props.setValues({
                              ...values,
                              checkEmail: true,
                             })
                            }
                          }
                        }
    

    【讨论】:

      【解决方案2】:

      我很确定没有办法使用 yup 进行检查。但是,您可以在您的数据库中搜索用户输入的电子邮件。如果未找到任何内容,则该电子邮件不存在。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-12
        • 2022-11-03
        • 2019-09-04
        • 1970-01-01
        • 1970-01-01
        • 2012-12-31
        • 2011-06-07
        • 2011-08-30
        相关资源
        最近更新 更多