As a developer, data validation is an essential part of your job. It is
important to ensure that the data users submit is accurate and in the correct
format. One of the most common types of data validation is email validation.
In this article, we will discuss email validation in Angular 8.

What is Email Validation?

email-validation

Email validation is the process of checking the format and validity of an
email address. It ensures that the email address provided by the user is in
the correct format and exists.

Email Validation in Angular 8

email-auto2-15
Angular 8 provides built-in email validation using the EmailValidator
directive. This directive can be used to validate email addresses in reactive
forms, template-driven forms, or even in custom validators.

Reactive Forms

In reactive forms, email validation can be added to a FormGroup by using the
FormControl class and the Validators.email method. Here is an example:

email = new FormControl('', [Validators.required, Validators.email]);

This code creates a new FormControl called email and adds the required and
email Validators to it. The required Validator ensures that the email field is
not empty, while the email Validator ensures that the email address is in the
correct format.

Template-driven Forms

In template-driven forms, email validation can be added to an input field by
using the ngModel directive and the email attribute. Here is an example:

<input type="email" name="email" [(ngModel)]="user.email" email required>

This code adds the email and required attributes to an input field called
email. The email attribute ensures that the email address is in the correct
format, while the required attribute ensures that the field is not empty.

Custom Validators

Custom validators can also be used to validate email addresses in Angular 8.
Here is an example:

export function emailValidator(control: AbstractControl): {[key: string]: any} | null {const emailRegex = /\S+@\S+\.\S+/;const valid = emailRegex.test(control.value);return valid ? null : {"invalidEmail': true};}

This code creates a custom validator called emailValidator that checks if the
email address is in the correct format. The valid variable stores the result
of the test, which is true if the email address is in the correct format and
false if it is not. The validator returns null if the email address is valid
and an object with the property 'invalidEmail' set to true if it is not.

Conclusion

Email validation is essential for ensuring that the data users submit is
accurate and in the correct format. Angular 8 provides built-in email
validation using the EmailValidator directive, which can be used in reactive
forms, template-driven forms, or even in custom validators.