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?
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
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
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,
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};
}
}