I am new in learning Angular2, and I want to make a validation form that verifies emails after a RegEx pattern.
My code looks something like this but I don\'t have a
For multiple email validation in a single field, you can do using the custom email validator.
import { FormControl } from '@angular/forms';
export class EmailValidator {
public static isValid(email) {
var 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,}))$/;
return re.test(String(email).toLowerCase());
}
static isMultiValid(control: FormControl): any {
console.log(control.value);
let tempEmail = control.value;
let invalid = false;
let regex =/[a-z0-9!#$%&'*+=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g;
if(tempEmail.indexOf(',') > -1){
var emails = control.value.split(',');
for (let email of emails) {
console.log(email);
let isValid = EmailValidator.isValid(email)
if(!isValid){
return{"email not valid":isValid}
}
}
return null;
}
else{
let email = control.value.split(',');
if( email == "" || ! regex.test(email)){
invalid = true;
return {
"email not valid": invalid
};
}
console.log("valid");
return null;
}
}
}
.
Angular 4 has a built-in "email" validation tag that can be added within the input. E.g.:
<input type="email" id="contactemail" email>
This will be valid for a series of numbers and letters then an @ then another series of letters. It will not account for the dot after the @ -- for that you can use the "pattern" tag within the input and your standard regex.
This pattern
worked for me :
pattern="[a-zA-Z0-9.-]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{3,}"