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?
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...