How to get list of validators which already applied on a fromgroup or formcontrol or formarray in angular7? I found setValidators(-) but there is no getValidators(-)..
Asked
Active
Viewed 1,432 times
3 Answers
0
Try this function
invalidControls(form) {
const invalid = [];
const controls = form.controls;
for (const name in controls) {
if (controls[name].invalid) {
invalid.push(name);
}
}
return invalid;
}

Ammar Hussain
- 294
- 2
- 13
0
Validator is simply a function. Angular compose all validators. When it's time to validate Angular call each validator function. You can access the function which compose them but not to each as they are encapsulated via closure.
Here is what I've found from angular sources.
This function is called whenever you create FormControl or set validators.
function coerceToValidator(
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null): ValidatorFn|
null {
const validator =
(isOptionsObj(validatorOrOpts) ? (validatorOrOpts as AbstractControlOptions).validators :
validatorOrOpts) as ValidatorFn |
ValidatorFn[] | null;
return Array.isArray(validator) ? composeValidators(validator) : validator || null;
}
composeValidators function is simply calling Validators.compose
compose method itself
static compose(validators: (ValidatorFn|null|undefined)[]|null): ValidatorFn|null {
if (!validators) return null;
const presentValidators: ValidatorFn[] = validators.filter(isPresent) as any;
if (presentValidators.length == 0) return null;
return function(control: AbstractControl) {
return _mergeErrors(_executeValidators(control, presentValidators));
};
}
and _executeValidators
function _executeValidators(control: AbstractControl, validators: ValidatorFn[]): any[] {
return validators.map(v => v(control));
}
As you can see are no access to them.

Steve
- 582
- 3
- 6
0
You can User This method for check validation
In .ts File
getAllErrors(form: FormGroup): { [key: string]: any; } | null {
let hasError = false;
const result = Object.keys(form.controls).reduce((acc, key) => {
const control = form.get(key);
const errors = (control instanceof FormGroup)
? this.getAllErrors(control)
: control.errors;
if (errors) {
acc[key] = errors;
hasError = true;
}
return acc;
}, {} as { [key: string]: any; });
return hasError ? result : null;
}
In .html file
<form id="form" [formGroup]="form" (ngSubmit)="ProjectSubmit(formProjectGeneralData.value,1)"
enctype="multipart/form-data">
<input type="text" formControlName="id" >
<span class="warning" *ngIf="getAllErrors(form)">
*required</span>
<input type="text" formControlName="name" >
<span class="warning" *ngIf="getAllErrors(form)">
*required</span>
</form>
Ignore my Styling
Hope this will helps ..!

DeC
- 2,226
- 22
- 42