Angular2 email validation

前端 未结 9 1873
既然无缘
既然无缘 2020-12-13 04:20

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

相关标签:
9条回答
  • 2020-12-13 04:46

    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;
    
       }
      }
    }
    

    .

    0 讨论(0)
  • 2020-12-13 04:47

    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.

    0 讨论(0)
  • 2020-12-13 04:47

    This pattern worked for me :

     pattern="[a-zA-Z0-9.-]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{3,}"
    
    0 讨论(0)
提交回复
热议问题