Generic email validator

后端 未结 10 904
灰色年华
灰色年华 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:31

    Yet another way to do this is using a custom directive. I like this approach as it's more consistent with the other ng2 validators.

    import { Directive, forwardRef } from '@angular/core';
    import { NG_VALIDATORS } from '@angular/forms';
    import { Validator, AbstractControl } from '@angular/forms';
    
    
    @Directive({
        selector: '[validateEmail][formControlName], [validateEmail][formControl],[validateEmail][ngModel]',
        providers: [
            { provide: NG_VALIDATORS, useExisting: forwardRef(() => EmailValidator), multi: true }
        ]
    })
    export class EmailValidator implements Validator {
    
        constructor() {
        }
    
        validate(c: AbstractControl) {
            let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
    
            return EMAIL_REGEXP.test(c.value) ? null : {
                validateEmail: {
                    valid: false
                }
            };
    
    
        }}
    

    Then usage in html is

提交回复
热议问题