I am wondering how I can add an validator to already created formControl (that was created with it own Validators). But, let's imagine that after some delay I want to add another one (or I have a custom control that contains a few validators itself) and I want to create outer Reactive form and add inner validators to outer.
Is it possible? I didn't found any information (only about re-setting all validators) Thanks for any help!
this.testForm = this.fb.group({
testField: [{value: '', disabled: false}, [<any>Validators.required]]
})
<form [formGroup]="testForm" novalidate>
<custom_input>
formControlName="testField"
[outerFormControl]="testForm.controls.testField"
</custom_input>
</form>
and after that I want to add other validator inside my custom controls. How I can do that?
custom_coontrol.ts
this.outerFormControl.push(Validators.maxLength(10));
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.
Dynamically Add Validators We need to listen to optionB value changes and based on that we add or remove the validators we require. We also call the control's updateValueAndValidity() method, as we need to recalculate the value and validation status of the control.
@Component({
selector: 'my-app',
template: `
<form [formGroup]="testForm" novalidate>
<input type="text" formControlName="age">
</form>
<button (click)="addValidation()">Add validation</button>
{{ testForm.valid | json }}
`,
})
export class App {
constructor(private fb: FormBuilder) {
this.testForm = this.fb.group({
age: [null, Validators.required]
})
}
addValidation() {
this.testForm.get('age').setValidators(Validators.maxLength(2));
}
}
Plunker
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