You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Firebase中创建新用户时能否捕获校验邮箱密码之外的更多字段?

问题根因说明

1. 自定义Alert不触发的原因

  • 你当前的前置校验逻辑中只调用了原生alert,没有设置setMessage和setError(true),自然不会触发MUI的Alert组件
  • register函数末尾有一行全局的setError(false),就算你在校验逻辑中设置了error为true,也会被这行代码同步覆盖状态,导致Alert无法显示
  • 你的校验逻辑中误用了单个&(位运算符),应该使用&&(逻辑与运算符),会导致判断结果不符合预期

2. Firebase Auth校验规则说明

Firebase Auth的createUserWithEmailAndPassword接口确实仅对邮箱格式、密码长度(默认最小6位)、邮箱是否已注册这三类和账号核心相关的规则做校验,你业务需要的姓名、电话、身份证号等自定义字段,Firebase不会做校验,必须在业务代码中自行前置校验。


修复方案

你可以把所有字段合法性校验都提前到调用Firebase接口之前,校验不通过直接设置错误状态并终止后续逻辑,catch块仅处理Firebase接口返回的错误即可,修改后的代码示例如下:

const register = (e) => {
  e.preventDefault();
  // 先做全字段前置校验
  if (firstName === "" && lastName === "") {
    setMessage("Por favor escriba su nombre y apellido");
    setError(true);
    return; // 校验不通过直接终止后续代码
  }
  if (firstName === "") {
    setMessage("Por favor escriba su nombre");
    setError(true);
    return;
  }
  if (lastName === "") {
    setMessage("Por favor escriba su apellido");
    setError(true);
    return;
  }
  if (email === "") {
    setMessage("Por favor escriba su correo electronico");
    setError(true);
    return;
  }
  if (phone === "") {
    setMessage("Por favor escriba su telefono celular o de casa");
    setError(true);
    return;
  }
  if (id === "" && idType === "Cédula") {
    setMessage("Por favor introduzca su cédula");
    setError(true);
    return;
  }
  if (id === "" && idType === "Pasaporte") {
    setMessage("Por favor introduzca su pasaporte");
    setError(true);
    return;
  }
  if (id === "") {
    setMessage("Por favor introduzca su cédula o pasaporte");
    setError(true);
    return;
  }
  if (password === "") {
    setMessage("Por favor introduzca su contraseña");
    setError(true);
    return;
  }
  if (password !== confirmsPassword) {
    setMessage("Las contraseñas no coinciden");
    setError(true);
    return;
  }
  if (password.length < 6) {
    setMessage("Su contraseña debe tener al menos 6 caracteres");
    setError(true);
    return;
  }

  // 所有校验通过后再调用Firebase接口
  auth.createUserWithEmailAndPassword(email, password)
    .then((authRes) => {
      if (authRes.user) {
        return authRes.user.updateProfile({
          displayName: firstName + " " + lastName,
        }).then(() => {
          return db.collection('usuarios').doc(authRes.user.uid).set({
            isAdmin: false,
            displayName: authRes.user.displayName,
            name: firstName,
            lastName: lastName,
            email: authRes.user.email,
            phone: parseFloat(phone),
            idType: idType,
            id: id,
            uid: authRes.user.uid,
            photoURL: `${AIBLogo}`,
          })
        })
      }
    })
    .then(() => {
      history.push("/")
    })
    .catch((e) => {
      // catch仅处理Firebase接口返回的错误
      if (e.message === "The email address is already in use by another account.") {
        setMessage("La dirección de correo electrónico ya está siendo utilizada por otra cuenta.")
      } else if (e.message === "The email address is badly formatted.") {
        setMessage("La dirección de correo electrónico está mal formateada")
      } else {
        setMessage("Ocurrió un error al crear la cuenta, por favor intente nuevamente")
      }
      setError(true);
    });
}

额外注意事项

  • 你的原代码中存在把用户明文密码存入Firestore的逻辑,这是严重的安全漏洞,Firebase Auth已经安全存储了用户的登录凭证,不需要你自己存密码,建议删除该字段。
  • 你用的MUI TextField已经加了required属性,也可以配合浏览器原生表单校验或者React Hook Form等表单库来简化校验逻辑,不需要手动写这么多if判断。

内容的提问来源于stack exchange,提问作者React Enjoyer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 06:57:04