172

According to RegExp documentation, we must use JavaScript (Perl 5) regular expressions : ECMA Specification. What method should I use in Dart to check if the input is an email?

My Car
  • 4,198
  • 5
  • 17
  • 50
Eric Lavoie
  • 5,121
  • 3
  • 32
  • 49
  • 6
    As of 2019: To properly support email validation in Dart/Flutter, please see the pub.dev package email_validator – Lance Oct 09 '19 at 20:47

11 Answers11

311

For that simple regex works pretty good.

const String email = "tony@starkindustries.com"

final bool emailValid = 
    RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
      .hasMatch(email);
Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76
Airon Tark
  • 8,900
  • 4
  • 23
  • 19
  • 9
    Best answer here. If you can't identify *all* valid emails, it is best to be lenient and not frustrate your users. – Jannie Theunissen Dec 31 '18 at 10:48
  • There are many valid characters in the local section, not included in this expression for example, the + operator isn't included such as a+b@c.d additional valid characters include !#$%&'*+-/=?^_`{|}~ and more are valid given additional restrictions – TheIT May 24 '19 at 02:02
  • 4
    For people looking at this as the highest upvoted answer at time of posting, this does not accept `name+filter@domain.com` which is how many users will automatically filter emails in their inbox. So don't use this unless you want to annoy them. If you want the most lenient regex, then use the accepted answer. Simple !== best. – DF_ Jul 22 '19 at 23:14
  • I am confident that this solution works for 99% of the use cases for general users. Not many users are familiar with `+` feature in email address. Also, disallowing it does not really forbid users from registering on the website. So this answer is fine for majority of use cases. – user482594 Sep 22 '19 at 05:33
  • Accepting `+` can be more troublesome if your backend system is not smart enough to ignore what comes after `+` when it wants to accept new users by each unique address. It could potentially allow an user to purposefully (or accidently) register to the system when they have already done, because they provided different suffixes (knowingly or without knowingly) after `+`. – user482594 Sep 22 '19 at 05:35
  • 6
    Among other things this regex won't allow hyphens in domain names: qweqwe@qwe-qwe.qw – Anton Duzenko Oct 31 '19 at 16:30
  • @user482594 That's not a valid concern. If the backend wants to eliminate users with the +filter they can just write a 2 line check for that. Anyway I run multiple sites with millions of users and I can tell you just by a quick cursory check it's more than 1%. – StackOverflowed Dec 04 '19 at 15:41
  • @StackOverflowed I am baffled to hear that it is not a valid concern. What I talked about happens in countless websites and that is how users abuse those systems with a single email address. You will be surprised to see how many systems fail to add that check to filter duplicate registrations. – user482594 Dec 04 '19 at 15:59
  • @user482594 Failing to check is on the website not the user. – StackOverflowed Dec 04 '19 at 16:20
  • @StackOverflowed which is exactly what I talked about in the earlier comment :) – user482594 Dec 04 '19 at 17:14
  • should be the accepted one – Kohls Feb 12 '20 at 16:24
  • it allows me to use hello@com Is it valid email? – kashlo Mar 25 '20 at 09:05
  • Duplicate character '.' inside character class – Gunaseelan Nov 06 '20 at 15:21
  • working good.... – gowthaman C Feb 23 '21 at 07:59
  • 6
    Note `test@subdomain.domain.com` will **NOT** work – chuang Apr 27 '21 at 18:05
  • 8
    Cool but I own a valid email: xxx@xxx-xx.com so the dash will not pass. This will allow '-' in the word after the '@' RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9-]+\.[a-zA-Z]+") – Gal Rom May 10 '21 at 13:07
  • 1
    @GalRom Thanks - nice when people contribute instead of wining – psimons Mar 06 '22 at 12:17
  • it is not valid for a@a-a.com – Abdulmalek Dery Feb 23 '23 at 15:25
118

Using the RegExp from the answers by Eric and Justin,
I made a extension method for String:

extension EmailValidator on String {
  bool isValidEmail() {
    return RegExp(
            r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$')
        .hasMatch(this);
  }
}

TextFormField(
  autovalidate: true,
  validator: (input) => input.isValidEmail() ? null : "Check your email",
)
763
  • 1,543
  • 1
  • 12
  • 15
  • not ";". it is "," isn't it? but yours are a good idea. – shinriyo Jun 14 '20 at 00:06
  • Yes,thanks for report.I fixed it – 763 Jun 14 '20 at 21:35
  • Perfeect, Dart Regexp doesn't work by copy pasting the regex from HTML5, your code has the fixes it needs to work properly, thank you for that! :D – Daniel Silva Feb 19 '21 at 20:26
  • For anyone coming in the year 2023+ this, in my personal opinion (not that anyone asked, but still :D) might be the best solution for an e-mail validator for **dart**. @763 will correct me if I'm wrong since I'm no regex guru, but on the last part of the regex, you can constrain the length of the domain (i.e.+[a-zA-Z] **{2, _5_ }** ), because the current regex allows you to enter 2> characters (.comcomcomcom, .netnet, .etcetcetc). Hope it helps. Cheers! – GrandMagus Feb 20 '23 at 18:07
  • @GrandMagus I cant say its good or not cause I m not guru at regex too :) – 763 Feb 25 '23 at 11:59
96

I'd recommend everyone standardize on the HTML5 email validation spec, which differs from RFC822 by disallowing several very seldom-used features of email addresses (like comments!), but can be recognized by regexes.

Here's the section on email validation in the HTML5 spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29

And this is the regex:

^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?)*$
Justin Fagnani
  • 10,483
  • 2
  • 27
  • 37
  • 2
    That's the same pattern I pasted, but I didn't mark it as code so it was escaped. If it still doesn't validate email addresses, that's something for the W3C to fix :) – Justin Fagnani Jun 08 '13 at 15:50
  • 4
    little late, but... It is not work - it`is valid for "s@s" string. – Zufar Muhamadeev Dec 19 '17 at 14:16
  • 12
    its valid for a@a – Airon Tark Jun 03 '18 at 06:17
  • 2
    While that is the one listed on the page, it allows `anything@anything`, which seems like a big oversight since as far as I know there are not any valid email addresses of that form. – Herohtar Feb 04 '19 at 02:03
  • 2
    They're all technically valid, according to the standard cf. https://serverfault.com/a/721929/530945 However, [ICANN did establish a rule against dotless domains in 2013.](https://www.icann.org/news/announcement-2013-08-30-en) [Which Google would like to change.](https://www.theregister.co.uk/2016/07/12/google_one_word_domains/) – Christopher Boyd Jul 09 '19 at 18:50
  • Beware the new domain extensions e.g. `.services` ```dart main() async { _checkEmail("a@a"); _checkEmail("a@a.a"); _checkEmail("s@asd,com"); _checkEmail("a@aa.co,uk"); _checkEmail("a@a.aa"); _checkEmail("a@aa.aa"); _checkEmail("aa@aa.aa.aa"); _checkEmail("aa.aa@aa.aa.aaaaaaaaa"); _checkEmail("aaaaaaaa-aaaaaaaaa.aaaaaaa@aaaaa-aaaaaa.aaaaaaa.aaaaaaaaa"); } _checkEmail(email){ bool emailValid = RegExp(r"^(?=^.{6,255}$)([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,85}$").hasMatch(email); print("${email.toString()} - ${emailValid.toString()}"); } ``` – loonix Feb 19 '21 at 14:14
  • 1
    The regex has been updated in the HTML standard since this answer was posted. The [new one](https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email)) is: RegExp(r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") – David Miguel Dec 21 '22 at 23:44
  • This answer is straight-up wrong. It doesn't enforce a domain extension and is out of date already. – Christian Findlay Jul 15 '23 at 00:28
39

I use this pattern : validate-email-address-in-javascript. (Remove slash / delimiters and add the Dart delimiters : r' ').

bool isEmail(String em) {

  String p = r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';

  RegExp regExp = new RegExp(p);

  return regExp.hasMatch(em);
}

EDIT :

For more information on email validation, look at these posts : dominicsayers.com and regular-expressions.info . This tool may also be very useful : gskinner RegExr.

EDIT : Justin has a better one. I'm using the pattern he proposed.

Community
  • 1
  • 1
Eric Lavoie
  • 5,121
  • 3
  • 32
  • 49
25

The best regEx pattern I've found is the RFC2822 Email Validation:

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

Taken from: regexr.com/2rhq7

All the other regEx I've tested, mark the string email@email as a positive, which is false.

David_E
  • 7,130
  • 4
  • 26
  • 29
14

I used a simple and not so rigorous validator which also allows anything@string.com and anything@string.co.in domains:

var email = "tony123_90874.coder@yahoo.co.in";
  bool emailValid = RegExp(r'^.+@[a-zA-Z]+\.{1}[a-zA-Z]+(\.{0,1}[a-zA-Z]+)$').hasMatch(email);
  print (emailValid);
12

2019 Correct Answer

To properly support email validation in Dart/Flutter, please see the pub.dev package email_validator.

Source: https://github.com/fredeil/email-validator.dart

_

This properly supports:

  • TLDs [optionally]
  • International Domains [optionally]
  • Filtered domains (e.g. user+filter@domain.name)
  • Domainless addresses (e.g. user@localhost)
Lance
  • 638
  • 1
  • 6
  • 22
  • 1
    I like this package, because if I typed `test@test` it would be considered wrong as I want. – Tayan Aug 21 '23 at 06:37
10

Email validation in Dart, follow the Regex:

bool validateEmail(String value) {
  Pattern pattern =
      r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
  RegExp regex = new RegExp(pattern);
  return (!regex.hasMatch(value)) ? false : true;
}

void main() {
  print(validateEmail("aslam@gmail.com"));
}

Flow the below Regex:

r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'

Reference: https://gist.github.com/aslamanver/3a3389b8ef88831128f0fa21393d70f0

Googlian
  • 6,077
  • 3
  • 38
  • 44
2

I have seen this page a few times when I was searching, and I came up with a simpler Regex for dart which might help those who will come to this page later.

here is the regex:

^[^@]+@[^@]+\.[^@]+

so in dart you can use it like

RegExp(r'^[^@]+@[^@]+\.[^@]+')

It only supports normal emails and not without TLD. for instance, me@email.com but not me@localhost. Hope it helps.

Majid
  • 2,507
  • 2
  • 19
  • 18
0

I have arrived to this page in search for e-mail validation, but none of the examples found here have passed all my tests.

Therefore I decided to write my own regEx, adapting some of the concepts from other answers (standing on shoulders of giants), and it is doing great so far:

^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9][a-zA-Z0-9-]{0,253}\.)*[a-zA-Z0-9][a-zA-Z0-9-]{0,253}\.[a-zA-Z0-9]{2,}$

If you find any issues with that pattern, please let me know.

bitfreeze
  • 58
  • 7
0

The best regular expression i've came across till now is the following:

r'([a-z0-9][-a-z0-9_+.][a-z0-9])@([a-z0-9][-a-z0-9.][a-z0-9].(com|net)|([0-9]{1,3}.{3}[0-9]{1,3}))'

this approach relies on adding every domain name you want your user to be able to log in with.

i just added com and net since they are the most popular ones but you can simply add more