Generic email validator

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

    Here is another way of validating a field using RegEx. You can bind a method to the keyUp event of the field.

    In your component:

    import {NgForm} from 'angular2/common';
    
    //...
    
    emailValidator(email:string): boolean {
        var EMAIL_REGEXP = /^(([^<>()\[\]\\.,;:\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,}))$/;
    
        if (!EMAIL_REGEXP.test(email)) {
            return false;
        }
        return true; 
    }
    

    In your HTML (view)

    Email address is invalid

    Another option (required field + validate when user leaves the field)

    This field is required
    Email address is invalid

    This method will work with any validation, so you could change the RegEx and validate Credit Card, Date, Time etc...

提交回复
热议问题