I want to create a form where the user will enter his email. I\'d like to validate email format client-side.
Is there any generic email validator in Angular 2?
Yet another way to do this is using a custom directive. I like this approach as it's more consistent with the other ng2 validators.
import { Directive, forwardRef } from '@angular/core';
import { NG_VALIDATORS } from '@angular/forms';
import { Validator, AbstractControl } from '@angular/forms';
@Directive({
selector: '[validateEmail][formControlName], [validateEmail][formControl],[validateEmail][ngModel]',
providers: [
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => EmailValidator), multi: true }
]
})
export class EmailValidator implements Validator {
constructor() {
}
validate(c: AbstractControl) {
let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
return EMAIL_REGEXP.test(c.value) ? null : {
validateEmail: {
valid: false
}
};
}}
Then usage in html is