Babulaas
Babulaas

Reputation: 869

Set validators to dynammic created formcontrol

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

Answers (2)

Babulaas
Babulaas

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

Naren Murali
Naren Murali

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)

TYPE:

new FormControl(formState?: any, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): FormControl

CODE:

this.formGroup.addControl('name', new FormControl('defaultvalue', [
      Validators.required,
      Validators.maxLength(15),
      Validators.pattern('')
    ]));

Upvotes: 0

Related Questions