Generic email validator

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

    I think nowadays you can use browser validation here. Email fields has a decent support and you can get validation result from element.validity.valid. You just need to pass this through the Angular custom validator

    See https://developer.mozilla.org/en-US/docs/Web/API/ValidityState and http://caniuse.com/#feat=input-email-tel-url for details

    0 讨论(0)
  • 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

    <input class="form-control" 
                   type="email"
                   [(ngModel)]="user.emailAddress" 
                   name="emailAddress" 
                   placeholder="first.last@example.com"
                   validateEmail
    
    0 讨论(0)
  • 2020-11-30 02:31

    I'm using : https://www.npmjs.com/package/ng2-validation

    npm install ng2-validation --save ng2-validation

    I'm not responding exaclty your question but for a lot of common scenarios you can find a custom validator already implemented

    example in your case : email : ['', [CustomValidators.email]]

    Best Reagards,

    0 讨论(0)
  • 2020-11-30 02:33

    I guess just now there is no email validator, but it's pretty easy to add a custom one. See this demo I used the same regex as angular1 uses.

    function emailValidator(control) {
      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 (!EMAIL_REGEXP.test(control.value)) {
        return {invalidEmail: true};
      }
    }

    0 讨论(0)
提交回复
热议问题