Email regex?

What is the correct email regex for a formBuilder validator? I was trying some examples from internet but none of them works

This is what I am trying:

email: ['', Validators.compose([Validators.minLength(4), Validators.maxLength(50), 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,}))$/'), Validators.required])],
1 Like

I created an email validator

import { FormControl } from '@angular/forms';
 
export class EmailValidator {
 
    static isValid(control: FormControl){
 
    	let re = /^(([^<>()\[\]\\.,;:\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,}))$/;
        let result = re.test(control.value);
        
        if (!result) {
        	return {
        		'email:validation:fail' : true
        	}
        }
        
        return null;
    }
 
}

Then import it into the page/component with your form and use it

email: ['', Validators.compose([Validators.required, EmailValidator.isValid])],
3 Likes

Im using this. Please try.

^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$

1 Like

this one isn’t working for me

this one works fine, but still accepts weird stuff like ---@gmail.com


  1. A-Z0-9a-z\._%+- ↩︎

It works for me in the context of the EmailValidator class - took that right out of my production code :slight_smile:

weird, why would it not work when directly typed into validator pattern?

not sure offhand, why not create the validator?

@FnnHuman I have made some changes. Have a look at this.

^[a-zA-Z0-9._]+[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$

1 Like

oh this one is even better, thanks