Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 950
Marc Avatar asked Oct 02 '16 16:10

Marc


People also ask

How do you know if a FormControl is required?

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 .

How will you add validators in 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.

How do you add a validator to FormControl dynamically?

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.


1 Answers

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; }; 
like image 156
Marcel Tinner Avatar answered Oct 12 '22 03:10

Marcel Tinner