Reputation: 869
I created a formControl with the following code:
this.formGroup.addControl('name', 'defaultvalue', Validators.required));
How can I add more validators to this control. Is it possible to add this here or do I have to make a method to add these validators. Can I use [Validators.required, Validators.maxLength(5)] in stead of Validators.required. Is it that simple or is this not the case
In my case I need maxlength and a regex.
I know I can use:
this.formGroup.get('name').setValidators([
Validators.required,
Validators.maxLength(15),
Validators.pattern('')
])
Upvotes: 1
Views: 33
Reputation: 869
It was that simple just put the validators in a array:
this.formGroup.addControl('name', 'defaultvalue', [Validators.required, Validators.maxLength(15)]));
Upvotes: 1
Reputation: 56054
Do you mean like this? The second argument can be the form control, first argument (formState) will be the initial value, second argument (validatorOrOpts) will be an array of validators (synchronous)
new FormControl(formState?: any, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): FormControl
this.formGroup.addControl('name', new FormControl('defaultvalue', [
Validators.required,
Validators.maxLength(15),
Validators.pattern('')
]));
Upvotes: 0