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
}

If you are looking for mobile/web Software Engineers to build you next projects, please Contact Nextfunc team here!

Tagged : / / /
Subscribe
Notify of
guest
5 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Michael
Michael
4 months ago

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

Subhash
Subhash
4 months 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'));
}
Denny Beulen
Denny Beulen
4 months 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!

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