This package provides the value type EmailAddress
to have a typed
representation of the e-mail address with the encapsulated validation.
-
Install the package as a dependency, running the command in the shell:
dart pub add email_address
-
Import the library:
import 'package:email_address/email_address.dart';
Parsing a EmailAddress
from string:
try {
final address = EmailAddress.parse('[email protected]');
} on EmailAddressFormatException {
// ...
}
Alternatively, you can use .parseOrNull()
:
assert(EmailAddress.parseOrNull('[email protected]') != null);
assert(EmailAddress.parseOrNull('not a e-mail address') == null);
When you need to, just check the format of the string without creating
an instance of the EmailAddress
:
assert(EmailAddress.validFormat('[email protected]') == true);
assert(EmailAddress.validFormat('not a e-mail address') == false);
Make case-insensitive check for equality of the addresses:
final address = EmailAddress.parse('[email protected]');
final sameAddressInUpperCase = EmailAddress.parse('[email protected]');
assert(address == sameAddressInUpperCase);
Convert the EmailAddress
back to string using .toString()
method as expected:
final address = EmailAddress.parse('[email protected]');
assert('[email protected]' == address.toString());