Dart/Flutter – How to validate an email address

In this post, I will show you an example of how to check if an input String is a valid email address using RegExp (regular expression).

/// Check if a String is a valid email.
/// Return true if it is valid.
bool isEmail(String string) {
  // Null or empty string is invalid
  if (string == null || string.isEmpty) {
    return false;
  }

  const pattern = r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$';
  final regExp = RegExp(pattern);

  if (!regExp.hasMatch(string)) {
    return false;
  }
  return true;
}

void main() {  
  print(isEmail('abc@mail.com')); // true
  print(isEmail('abc@mail.com.vn')); // true
  print(isEmail('abc-x@mail.com')); // true
  print(isEmail('123abc@mail.com')); // true
  print(isEmail('test----100@mail.com')); // true
  print(isEmail('100a@mail.com')); // true
  print(isEmail('100@mail.com')); // true

  print(isEmail('test@mail.com@net')); // false
  print(isEmail('abc@mail.com.vn-abc')); // false
}
Tagged : / / /
Subscribe
Notify of
guest

6 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Michael
Michael
2 years ago

Thank you very much! This helped me in my assignment!

Subhash
Subhash
3 years ago

now flutter provides a package for email validation.

dependencies:
email_validator: ^1.0.6

———————————————————
import ‘package:email_validator/email_validator.dart’;


———————————————————

import 'dart:core';
import 'package:email_validator/email_validator.dart';

void main() {
    const String email = 'fredrik.eilertsen@gail.com';
    final bool isValid = EmailValidator.validate(email);

    print('Email is valid? ' + (isValid ? 'yes' : 'no'));
}
Nawak
Nawak
Reply to  Subhash
2 years ago

Hi,

I think you haven’t seen the source code of this package or you don’t mind the useless code

Denny Beulen
Denny Beulen
3 years ago

The first return should obviously be a return false; when the string is empty or null it should not return true.

For the rest, thanks for the code!

6
0
Would love your thoughts, please comment.x
()
x