I have currently facing an issue of getting the email valdiated properly:
If I set "Validators.email" then: me@host is validated to true, which is not suitable in my case.
me@host should not validate,
[email protected] should validate.
I have tried the following two methods, none of them are helping. Only required is being validated properly but not the email validation.
Email: new FormControl('', [ Validators.required, Validators.pattern('^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+$')
])
Email: new FormControl('', Validators.compose([ Validators.required, Validators.pattern('^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+$')
]))solutions please...
23 Answers
I'm using like below to validate an email
/** * Actual validator function * @param ctrl FormControl that contains the input validation state */ return function emailValidator(ctrl: FormControl) { if (ctrl && ctrl.value) { const value: string = ctrl.value; // tslint:disable-next-line const regEx = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ // tslint:disable-next-line const isValidEmail = regEx.test(value) // signify to the Angular form control whether the value is valid return isValidEmail ? null : { email: true }; } };
} 1 You need to escape the backslash to the dot in your regex. Use \\. instead of \.
Validators.pattern('^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]+$') I think you are not setting type=email in your input element in your HTML
<input type="email" name="Email" [formControl]="form.controls['Email']" />Also, you need not use a pattern to validate an email, you can simply set the email as one of the validators as below,
this.form = this.formBuilder.group({ Email: ["", Validators.compose([Validators.required, Validators.email])]
}); 1