Custom validations
We can expand the use of validations and create custom functions that can even receive parameters to maximize reuse in our projects. To illustrate this, let’s create a custom validation to evaluate whether the number of repetitions or sets are multiples of two and three, respectively.
Let’s create a new file called custom-validation.ts
and add the following function:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; export function multipleValidator(multiple: number): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { const isNotMultiple = control.value % multiple !== 0; return isNotMultiple ? { isNotMultiple: { value: control.value } } : null; }; }
For Angular to recognize the form validation function, it must return a new function with the signature described in the ValidatorFn
interface. This signature...