Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 643
toothful Avatar asked Jan 01 '23 16:01

toothful


1 Answers

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.

like image 116
Arm144 Avatar answered Jan 03 '23 06:01

Arm144