Categories
Angular

Angular Reactive form Validations

Validating input in reactive forms

Validator functions
Validator functions can be either synchronous or asynchronous.

Sync validators: Synchronous functions that take a control instance and immediately return either a set of validation errors or null. You can pass these in as the second argument when you instantiate a FormControl.

Async validators: Asynchronous functions that take a control instance and return a Promise or Observable that later emits a set of validation errors or null. You can pass these in as the third argument when you instantiate a FormControl.

Example:
ngOnInit():{
   this.heroForm = new FormGroup({
    'name': new FormControl('',[Validators.required,  Validators.minLength(4)]),
     'alterEgo': new FormControl(''),
     'power': new FormControl('', Validators.required)
   });
}
get name() { return this.heroForm.get('name'); }
get power() { return this.heroForm.get('power'); }

Template File

<input id="name" formControlName="name" />
<div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
 <div *ngIf="name.errors.required">Name is required.</div>
 <div *ngIf="name.errors.minlength">Name must be at least 4 characters long.</div>
</div>
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
createUserform: FormGroup;
export const email = /^[a-zA-Z0-9_]{1,}$/;
this.createUserform = new FormGroup({
	firstname: new FormControl('', [Validators.required, Validators.minLength(3)]),
	lastname: new FormControl('', [Validators.required, Validators.minLength(3)]),
	email: new FormControl('', Validators.compose([Validators.required, 
Validators.email, Validators.pattern(email)])),
});
<div *ngIf="createUserform.controls['firstname'].invalid 
&& (createUserform.controls['firstname'].dirty 
|| createUserform.controls['firstname'].touched)" class="error formError">
 <div *ngIf="createUserform.controls['firstname'].errors.required">
First Name is required.
</div>
 <div *ngIf="createUserform.controls['firstname'].errors?.minlength">
First Name should be minimum 3 characters.
</div>
            </div>