Angular2: Find out if FormControl has required validator?
This function should work for FormGroups and FormControls
export const hasRequiredField = (abstractControl: AbstractControl): boolean => { if (abstractControl.validator) { const validator = abstractControl.validator({}as AbstractControl); if (validator && validator.required) { return true; } } if (abstractControl['controls']) { for (const controlName in abstractControl['controls']) { if (abstractControl['controls'][controlName]) { if (hasRequiredField(abstractControl['controls'][controlName])) { return true; } } } } return false;};
While there is no Angular API to directly find if the required
validator is set for a particular field, the roundabout way to achieve this is like as below:
import { NgForm, FormControl } from '@angular/forms';const isRequiredControl = (formGroup: NgForm, controlName: string): boolean => { const { controls } = formGroup const control = controls[controlName] const { validator } = control if (validator) { const validation = validator(new FormControl()) return validation !== null && validation.required === true } return false}
I have tested this and this triggers only if the Validator.Required
validator is added to the particular FormControl
.
There is no method how to check validators or get all validators: https://github.com/angular/angular/issues/13461
@fairlie-agile solution is pretty clever. But I think we have to use empty FormControl because we need fire required validator and this.group.controls[this.config.name]
could be already initialized with some value.
ngOnInit() { let formControl = this.group.controls[this.config.name]; let errors: any = formControl.validator && formControl.validator(new FormControl()); this._required = errors !== null && errors.required;}