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
validator({} as AbstractControl); This will return an Object with the list of validators that are present on your FormControl . You can then check for the required key in the Object. If it exists and its value is true then you can be sure that a Required Validator is applied on the FormControl .
Adding async validators to reactive formslink To use an async validator in reactive forms, begin by injecting the validator into the constructor of the component class. Then, pass the validator function directly to the FormControl to apply it.
We can add Validators dynamically using the SetValidators or SetAsyncValidators. This method is available to FormControl, FormGroup & FormArray. There are many use cases where it is required to add/remove validators dynamically to a FormControl or FormGroup.
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; };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With