'Angular 7 email validation using regex on reactive form

On Angular, I am trying to validate email using following 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,}))$

Like below -

createGroupForm() {
    this.childGroupForm = new FormGroup({
        'groupName': new FormControl(null, Validators.compose([
            Validators.required
        ])),
        'groupEmail': new FormControl(null, Validators.compose([
            Validators.pattern('^(([^<>()[\]\\.,;:\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,}))$')
        ]))
    });
}

But looks like it's not working. It always display "Email is invalid.", even though it is valid.



Solution 1:[1]

I made an example here: https://stackblitz.com/edit/angular-pgc7st

So in the Validator it should be like this:

Validators.pattern(/^(([^<>()[\]\\.,;:\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,}))$/)

If you see in you code you are entering an string as reexp. so removing the string char ('') it works. Check the example.

Solution 2:[2]

Regex in javascript should not be passed as a string but should have / at start and end like:

/^(([^<>()[\]\\.,;:\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,}))$/

so try this:

createGroupForm() {
    this.childGroupForm = new FormGroup({
        'groupName': new FormControl(null, Validators.compose([
            Validators.required
        ])),
        'groupEmail': new FormControl(null, Validators.compose([
            Validators.pattern(/^(([^<>()[\]\\.,;:\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,}))$/)
        ]))
    });
}

Read more

Solution 3:[3]

You can use this regx. I hope it will works for you.

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

Solution 4:[4]

Try this. It run well.

^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arm144
Solution 2 Mustahsan
Solution 3 Komal Sakhiya
Solution 4 Suraj Rao