Home > other >  Angular: get list of all validators from a FormControl
Angular: get list of all validators from a FormControl

Time:09-25

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!

CodePudding user response:

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

  • Related