Generic email validator

后端 未结 10 924
灰色年华
灰色年华 2020-11-30 02:01

I want to create a form where the user will enter his email. I\'d like to validate email format client-side.

Is there any generic email validator in Angular 2?

10条回答
  •  醉酒成梦
    2020-11-30 02:12

    You can use Form Directives and Control to do this.

    export class TestComponent implements OnInit {
         myForm: ControlGroup;
         mailAddress: Control;
    
         constructor(private builder: FormBuilder) {
             this.mailAddress = new Control(
                "",
                Validators.compose([Validators.required, GlobalValidator.mailFormat])
            );
         }
    
         this.addPostForm = builder.group({
                mailAddress: this.mailAddress
         });
    }
    

    Import:

    import { FormBuilder, Validators, Control, ControlGroup, FORM_DIRECTIVES } from 'angular2/common';
    

    Then your GlobalValidator class:

    export class GlobalValidator {
    
        static mailFormat(control: Control): ValidationResult {
    
            var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
    
            if (control.value != "" && (control.value.length <= 5 || !EMAIL_REGEXP.test(control.value))) {
                return { "incorrectMailFormat": true };
            }
    
            return null;
        }  
    }
    
    interface ValidationResult {
        [key: string]: boolean;
    }
    

    And then your HTML:

    mailAddressis required.

    Email format is invalid.

    For more information about this, you can read this good article : https://medium.com/@daviddentoom/angular-2-form-validation-9b26f73fcb81#.jrdhqsnpg or see this github project for a working example.

    (edit : that reg ex does not seem to check for a dot in the domain

    I use this one instead

    /^(([^<>()\[\]\\.,;:\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,}))$/
    

    cfr http://emailregex.com/

提交回复
热议问题