<div *ngIf="name.errors && (name.dirty || name.touched)"
class="alert alert-danger">
<div [hidden]="!name.errors.required">
Name is required
</div>
<div [hidden]="!name.errors.minlength">
Name must be at least 4 characters long.
</div>
<div [hidden]="!name.errors.maxlength">
Name cannot be more than 24 characters long.
</div>
</div>
import { FormControl } from '@angular/forms';
function validateEmail(c: FormControl) {
let EMAIL_REGEXP = ...
return EMAIL_REGEXP.test(c.value) ? null : {
validateEmail: {
valid: false
}
};
}
import {Component, OnInit} from '@angular/core'
@Component(
// ...
)
export class Cmp {
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form = new FormGroup({
name: new FormControl('', Validators.required)),
street: new FormControl('', Validators.minLength(3)),
city: new FormControl('', Validators.maxLength(10)),
zip: new FormControl('', Validators.pattern('[A-Za-z]{5}')),
email: new FormControl('', validateEmail)
});
}
}
import { Directive } from '@angular/core';
import { NG_VALIDATORS } from '@angular/forms';
@Directive({
selector: '[validateEmail][ngModel]',
providers: [
{ provide: NG_VALIDATORS, useValue: validateEmail, multi: true }
]
})
class EmailValidator {}
import { EmailValidator } from './email.validator';
@NgModule({
...
declarations: [AppComponent, EmailValidator],
})
export class AppModule {}
<form novalidate>
...
<input type="email" name="email" ngModel validateEmail>
</form>