How to Validate Email Address with Angular

How to validate emails using typescript and angular form validation


Email Validation in a Nutshell

An Email Address can look right but still be wrong and bounce. Real Email uses in depth email address validation to check if emails really exist without sending any messages.

Checking Formatting

You can use a regular expression to check if an email address is formatted correctly. In the Angular web framework you can use the built in Validators.email.

emailFormControl = new FormControl("", [Validators.email]);

Async Form Validation using Real Email API

You can use the Real Email API with an angular async validator to do in depth email address inspections to check that the address really exists on the email server. This example uses angular reactive form validation but can also be done with template forms. The angular ecosystem has rich features for form validation and this approach allows you to use that.

csv upload

The main steps to build an async validator are.

  • define the validator
  • add it to the angular module
  • use it in the reactive Form Control

Async Email Validator

@Injectable({ providedIn: "root" })
export class AsyncEmailValidator implements AsyncValidator {
private apiKey?: string; // put your api key here
constructor(private http: HttpClient) {}

validate(ctrl: AbstractControl): Promise<ValidationErrors | null> {
if (ctrl.value) {
return this.http
.get<{ status: string }>(
"https://isitarealemail.com/api/email/validate",
{
params: { email: ctrl.value },
headers: {
Authorization: this.apiKey ? "Bearer " + this.apiKey : [],
},
}
)
.toPromise()
.then((result) => {
if (result.status === "invalid") {
return { invalid: true };
} else if (result.status === "unknown") {
return { invalid: true };
} else {
// status is valid
return null;
}
});
} else {
return Promise.resolve({ invalid: true });
}
}
}

Add the validator to the angular module

@NgModule({
providers: [AsyncEmailValidator]
})

In your component define the FormControl wiring in the emailValidator.

constructor(readonly emailValidator: AsyncEmailValidator) {}

emailFormControl = new FormControl('', {
updateOn: 'blur',
asyncValidators: [this.emailValidator.validate.bind(this.emailValidator)],
});

Define your input field as a normal angular form field.

<input [formControl]="emailFormControl" />

Using API Key

You will be able to test 100 emails per day, if you have more that that you will need to signup and get an API key. An email might be 'unknown' if the email server is unresponsive. With an API key you will be able to test lots of emails each day.

export class AsyncEmailValidator implements AsyncValidator {
private apiKey = "xxx..." // todo replace with your api key

Get started with Real Email validations today.