电子邮件地址格式不正确 Firebase(Flutter)

huangapple go评论71阅读模式
英文:

The email address is badly formatted Firebase (Flutter)

问题

我已阅读所有相关的帖子和答案,但未找到解决方法。我有几个用于验证电子邮件和密码的类,还有字符和密码长度的验证,我可以成功注册一个新用户,但我无法使用新注册用户的电子邮件和密码登录帐户,因为我收到以下错误消息:“初始任务失败,操作为RecaptchaAction(action=signInWithPassword)异常 - 电子邮件地址格式不正确。” 此外,我使用print检查了在尝试登录时输入到函数的输入并传递到Firebase的内容,我发现没有额外的空格、不正确的字符等。我的代码如下:

class Validator {
  final _emailRules =
      RegExp(r'^[\w-]+(\.[\w-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,})$');
  final _passwordRules = RegExp(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$');

  String validateEmail(String email) {
    if (email.isEmpty) {
      return 'Email cannot be empty';
    } else if (!_emailRules.hasMatch(email)) {
      return 'Please enter a valid email';
    }
    return '';
  }

  String validatePassword(String password) {
    if (password.isEmpty) {
      return 'Password cannot be empty';
    } else if (!_passwordRules.hasMatch(password)) {
      return 'Password should be 8 digits, including uppercase letters';
    }
    return '';
  }
}

Future<User?> signInUser(String email, String password) async {
  UserCredential userCredential = await _firebase.signInWithEmailAndPassword(
      email: email.trim(), password: password.trim());
  User? user = userCredential.user;
  if (user != null) {
    String token = await user.getIdToken();
    await storage.write(key: 'token', value: token);
  }
  return user;
}

bool _validateFields(BuildContext context) {
  String emailError = Validator().validateEmail(_emailController.text);
  String passwordError = Validator().validatePassword(_passwordController.text);

  if (emailError.isNotEmpty) {
    showSnackBarError(context, emailError);
    return false;
  }

  if (passwordError.isNotEmpty) {
    showSnackBarError(context, passwordError);
    return false;
  }

  return true;
}

SizedBox(
  width: double.infinity,
  child: OutlinedButton(
    onPressed: () {
      if (_validateFields(context)) {
        String email = _emailController.text.trim();
        String password = _passwordController.text;
        BlocProvider.of<AuthBloc>(context).add(
          SignInEvent(email: email, password: password),
        );
        print(email);
        print(password);
      }
    },
    child: const Text('Sign In'),
  ),
)

但是,当我在signIn方法中使用硬编码的值(之前已在Firebase中添加)时,它完全正常工作。

编辑: 我找到了解决方案,我相当愚蠢。我混淆了在引用signInUser的地方的密码和登录位置。我应该做的只是修复问题,它就可以正常工作了。它之前是

userSignIn = await fireBaseService.signInUser(event.password, event.email);

但应该是

userSignIn = await fireBaseService.signInUser(event.email, event.password);
英文:

I’ve read all the related posts and answers here and haven’t found a solution for myself. I have several classes for email and password validation, also there is verification for characters and password length, I can successfully register a new user, but I can not log in to an account under the email and password of a newly registered user because I get this error: Initial task failed for action RecaptchaAction(action=signInWithPassword)with exception - The email address is badly formatted.
Also using the print I checked that gets on the input to the function and transferred to the firebase when trying to sign in and I found that there are no extra spaces, incorrect characters and so on. My code looks like this:

class Validator {
  final _emailRules =
  RegExp(r&#39;^[\w-]+(\.[\w-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,})$&#39;);
  final _passwordRules = RegExp(r&#39;^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$&#39;);

  String validateEmail(String email) {
    if (email.isEmpty) {
      return &#39;Email cannot be empty&#39;;
    } else if (!_emailRules.hasMatch(email)) {
      return &#39;Please enter a valid email&#39;;
    }
    return &#39;&#39;;
  }

  String validatePassword(String password) {
    if (password.isEmpty) {
      return &#39;Password cannot be empty&#39;;
    } else if (!_passwordRules.hasMatch(password)) {
      return &#39;Password should be 8 digit, uppercase letters&#39;;
    }
    return &#39;&#39;;
  }
}

sign in method:

  Future&lt;User?&gt; signInUser(String email, String password) async {
    UserCredential userCredential = await _firebase.signInWithEmailAndPassword(
        email: email.trim(), password: password.trim());
    User? user = userCredential.user;
    if (user != null) {
      String token = await user.getIdToken();
      await storage.write(key: &#39;token&#39;, value: token);
    }
    return user;
  }

checking for password/emeil inputs are correct

 bool _validateFields(BuildContext context) {
    String emailError = Validator().validateEmail(_emailController.text);
    String passwordError = Validator().validatePassword(_passwordController.text);

    if (emailError.isNotEmpty) {
      showSnackBarError(context, emailError);
      return false;
    }

    if (passwordError.isNotEmpty) {
      showSnackBarError(context, passwordError);
      return false;
    }

    return true;
  }

at least the bloc of code with sending to Firebase email/password:

 SizedBox(
              width: double.infinity,
              child: OutlinedButton(
                onPressed: () {
                  if (_validateFields(context)) {
                    String email = _emailController.text.trim();
                    String password = _passwordController.text;
                    BlocProvider.of&lt;AuthBloc&gt;(context).add(
                      SignInEvent(email: email, password: password),
                    );
                    print(email);
                    print(password);
                  }
                },
                child: const Text(&#39;Sign In&#39;),
              ),
            )

But then I use hardcoded value for email/password in signIn method (previously added it in Firebase) it works perfectly well.

EDIT: I found solution and I was pretty dumb. I was mixed up places of password and login in place where I refer to signInUser. All I should to do is fix the problem and it worked. it was final

userSignIn = await fireBaseService.signInUser(
           event.password, event.email);

BUT it should be final

userSignIn = await fireBaseService.signInUser(
            event.email, event.password);

答案1

得分: 1

错误基本上意味着输入的电子邮件不是 Firebase 接受的正确格式。

如上面的评论建议,在将电子邮件发送到 Firebase 之前添加一个断点,并打印电子邮件的值。

我想要添加的另一个小建议是使用一个用于验证电子邮件的包,叫做 email_validator。我从未担心过电子邮件的验证,只需使用这个包即可。

P.S. 如果验证器正常工作,那么您将不再需要修剪该值。

以下是 email validator 的简单用法:

TextFormField(
...
validator: (value){
 if (EmailValidator.validate(value!)) { 
  return null;
  } else {
  return "请输入有效的电子邮件";
  }
},
...
),

希望这对您有帮助!

英文:

The error basically implies that the email entered is not a proper format that is accepted by firebase.

As suggested in the above comment add a breakpoint before sending the email to firebase and print the email value.

Another small suggestion that I would like to add is to use a package for validating your email called email_validator. I have never had to worry about validating the email and simply use this package.

P.s. If the validator is working correctly then you will not require to trim the value anymore.

Here is the simple usage of email validator:

TextFormField(
...
validator: (value){
 if (EmailValidator.validate(value!)) { 
  return null;
  } else {
  return &quot;Please enter a valid email&quot;;
  }
},
...
),

Hope this helps you out!

huangapple
  • 本文由 发表于 2023年7月13日 18:50:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76678537.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定