Angular Email Validation Pattern to strictly enforce the pattern

Viewed 699

Am trying to use a pattern to validate my email input from the user through a form control.

I use the following to validate email id entered by the user.

'email': ['', [Validators.required, Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,4}$")]]

But when enter "abc@abcd" the form become valid and allow the user to submit. I can see that the pattern is not respected here. How can I force the email to be validated according to the pattern defined?

2 Answers

You can use the following regex expression in order to validate an email correctly.

Regex:

/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/

If you are using Angular Reactive forms in order to do the validation. Regex will be added like below.

email: [
    null,
    Validators.compose([
      Validators.required,
      Validators.pattern(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/),
    ]),
  ]

These are the failure scenarios for the above regex.

  • abc
  • abc@cde
  • abc@cde.f

Success scenarios

  • abc@cde.fg

email regex pattern

"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"

OR

new RegExp("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*")
Related