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
beck24
August 18, 2017, 9:54am
2
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
beck24:
^(([^<>() \.,;:\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,}))$
this one isnβt working for me
this one works fine, but still accepts weird stuff like ---@gmail.com
beck24
August 18, 2017, 10:41am
5
It works for me in the context of the EmailValidator class - took that right out of my production code
weird, why would it not work when directly typed into validator pattern?
beck24
August 18, 2017, 11:11am
8
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