Angular 4 Reactive form Builder and Validation Management/Types
Validators can be applied by simply using their corresponding directives. To make these directives available, we need to import Angular’s FormsModule to our application module first
import { NgModule } from ‘@angular/core’;
import { BrowserModule } from ‘@angular/platform-browser’;
import { FormsModule } from ‘@angular/forms’;
import { FormGroup, FormBuilder, Validators } from ‘@angular/forms’;
@NgModule({
imports: [BrowserModule, FormsModule], // we add FormsModule here
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule {}
Below is sample build form to show you how to implement validation for form for each field.
constructor(private formBuilder: FormBuilder) {
this.userForm = this.formBuilder.group({
‘name’: [”, Validators.required],
’email’: [”, [Validators.required]],
‘profile’: [”, [Validators.required, Validators.minLength(10)]]
});
}
The supported validators for reactive form are:
Validators.required – Field is mandatory
Validators.minLength(10) – Entered value should have min length of 10 character
Validators.maxLength(10) – Entered value should have max length of 10 character
Validators.pattern(‘[A-Za-z]{5}’) – Specify pattern to validate entered data
Custom Validator – You create your own Custom Validator based on requirement