Angular2: Find out if FormControl has required validator?
does someone know a way to find out for an Angular2 FormControl if the required validor is registered for the control.
this.form = builder.group({name: ['', Validators.required]};
Can I then query the this.form.controls['name']
control if it is a required field? I know I can check if it is valid, but that's not what I want.
Kind regards, Marc
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
.
Angular now provides hasValidator
with which you can check if a formcontrol has a sync validator. If you happen to need to check if it has an async validator, that also exist with hasAsyncValidator
.
In your case when you want to check if the formcontrol is required, you can do:
this.form.get('name').hasValidator(Validators.required);