In ngular-13 I have this code
validation-errors.ts:
import { ValidationErrors } from "@angular/forms";
import { FormArray, FormControl, FormGroup, ValidatorFn } from '@angular/forms';
// Defines a stronger typed validation error model, compatible with the Angular default.
export interface ValidationError extends ValidationErrors {
[validatorName: string]: {
message: string
}
}
validation.component.ts :
import { ValidationError } from '../models/validation-error';
export class CustomValidators {
static requiredMinNumber(min: number): ValidatorFn {
return (c: FormControl): ValidationError | null => {
if (this.isEmpty(c.value))
return this.makeError('requiredMinNumber', `You must provide a number of at least ${min}.`);
else if (!this.isNumber(c.value))
return this.makeError('requiredMinNumber', `Value must be a number, and minimum ${min}.`);
else if (c.value < min)
return this.makeError('requiredMinNumber', `The minimum accepted value is ${min}.`);
return null;
};
}
}
But this error occurred:
Type '(c: FormControl) => ValidationError | null' is not assignable to type 'ValidatorFn'.
Types of parameters 'c' and 'control' are incompatible.
Type 'AbstractControl' is not assignable to type 'FormControl'.ts(
How do I get it resolved?
Thanks
CodePudding user response:
To write a custom validator, you must follow ValidationFn
interface.
interface ValidatorFn {
(control: AbstractControl): ValidationErrors | null
}
Change c
as AbstractControl
type.
static requiredMinNumber(min: number): ValidatorFn {
return (c: AbstractControl): ValidationError | null => {
...
};
}