I worked on Angular Form group and Form controls validation recently. we can validate the whole form controls at one go with angular cross field validation technique.
Fundamentals & Reference :
Angular Reactive Forms:
https://angular.io/guide/reactive-forms
Validation with custom validators for whole form:
https://angular.io/guide/form-validation#cross-field-validation
All we have to do is supply the certain options to new FormGroup() constructor.
So, today we talk about two such properties of FormGroup
1) Validators:
This property is used to pass custom validator function. we create the validation functions as a directive which implements ValidatorFn interface of angular . It takes an Angular control object as an argument and returns either null if the form is valid, or
ValidationErrors
otherwise.Note: Data cloned from the official angular documentaion .
Example :
Form Group :
const heroForm = new FormGroup({ 'name': new FormControl(), 'alterEgo': new FormControl(), 'power': new FormControl() });To add a validator function . give option like below:
const heroForm = new FormGroup({ 'name': new FormControl(), 'alterEgo': new FormControl(), 'power': new FormControl() }, { validators: identityRevealedValidator });Here identityRevealedValidator is a cross field validator function writte in a separate directive like below
Directive:
export const identityRevealedValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => { const name = control.get('name'); const alterEgo = control.get('alterEgo'); return name && alterEgo && name.value === alterEgo.value ? { 'identityRevealed': true } : null;};Template goes like this to show errors:
<div *ngIf="heroForm.errors?.identityRevealed && (heroForm.touched || heroForm.dirty)" class="cross-validation-error-message alert alert-danger">
Name cannot match alter ego. </div>
Now Lets talk about another property of FormGroup
2) updateOn
> Reports the update strategy of the
AbstractControl
(meaning the event on which the control updates itself). Possible values: 'change'
| 'blur'
| 'submit'
Default value: 'change'
> Can be used for formControl / formGroup
submit:
> updates the formGroup values on submit instead each blur / change event
blur:
> on blur , the values get updated for formGroup / formControl based on given context.
change:
> On control change the values get updated.
In our above example, if we want to update formGroup values on submit then
const heroForm = new FormGroup({
'name': new FormControl(), 'alterEgo': new FormControl(), 'power': new FormControl() }, { validators: identityRevealedValidator , updateOn: 'submit' });
// the above will set updateOn:'submit/blur/change' for all controls as they are grouped under one formGroup.