2

I might be wrong here, but after a bit of research it seems impossible to extract the list of validators from a FormControl

const ctrl = new FormControl(null,[Validators.minLength(8), Validators.required]});

I would like a list with these validators, so I can do something like this (in theory)

const validators = ctrl.getValidators();
ctrl.setValidators( [...validators, myOwnValidator]);

Ideally I would like to append a validator, but as far as I know that is not possible.

I found two suggestions on the internet to access the validators on a FormControl:

1)

const validator = ctrl.validator('' as any as AbstractControl);
// -> {required: true}
  1. const validator = ctrl.validator({} as AbstractControl); // -> {required: true}

Both options do exactly the same thing, they return an object with just one key required and a value true. Not very useful because I don't see anything about the other validator and I need the validator classes (because I need to set the validators again).

What I have found so far is not very useful, so I was wondering if I missed something. So any help would be appreciated!

7
  • Why would you want to put all validators in one variable ? Commented Sep 24, 2021 at 10:54
  • you mean that validators const? Because I need to add another validator, so I need all the existing ones. Commented Sep 24, 2021 at 10:58
  • Could you tell me what's the goal ? What you want to do on your formControl now or in the future ? Commented Sep 24, 2021 at 11:01
  • which version of angular do you use? Commented Sep 24, 2021 at 11:04
  • I'm using angular 12.1.0 Commented Sep 24, 2021 at 11:08

1 Answer 1

2

Solution for Angular 12.2.0

this.form.controls["firstName"].addValidators([Validators.minLength(1), Validators.maxLength(30)]);

enter image description here

Solution for angular 11 and below

you can define validators for specific control into variable and then reuse it

public ctrlDefaultValidators = [Validators.minLength(8), Validators.required];
public ctrl = new FormControl(null, ctrlDefaultValidators});

ctrl.setValidators( [...ctrlDefaultValidators , myOwnValidator]);

ps: dont forget to call updateValueAndValidity

Sign up to request clarification or add additional context in comments.

4 Comments

Do you have a link to the angular documentation, because I can't find anything about addValidators
sorry, it is not present in your version, it is added in v12.2.0. github.com/angular/angular/blob/master/…
@shutsman Please create an answer for all the future poor lost souls working on Angular versions older than 12.2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.