Home > Mobile >  How to validate email after @ in flutter?
How to validate email after @ in flutter?

Time:06-21

How can I validate email after @ in email address ? I need to show error if user input only "username@".

String emailValidator(String email, BuildContext context) {
  if (email == null || email.length == 0) {
    return AppLocalizations.of(context).translate('validators.requiredField');
  }

  if (email == null || !email.contains("@")) {
    return AppLocalizations.of(context).translate('validators.invalidEmail');
  }

  return null;
}

CodePudding user response:

Use email_validator package of flutter

CodePudding user response:

I think regex would be the best option for that. Adding a package for this easy task seems like too much overhead for me.

This question has been answered lots of times here

The expression:

bool emailValid = RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'* -/=?^_`{|}~] @[a-zA-Z0-9] \.[a-zA-Z] ").hasMatch(email);

CodePudding user response:

You can use regex

Create an extension on String

extension RegexExt on String {
  bool validateEmail() => RegExp(
          r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'* -/=?^_`{|}~] @[a-zA-Z0-9] \.[a-zA-Z] ")
      .hasMatch(this);
}

Usage

String emailValidator(String email, BuildContext context) {
  if (email == null || email.length == 0) {
    return AppLocalizations.of(context).translate('validators.requiredField');
  }

  return email.validateEmail() ? null : AppLocalizations.of(context).translate('validators.invalidEmail'); 
}

CodePudding user response:

Did you try using email_validator package? it is very simple and can achieve what you want

  • Related