-2

How do I add or push to an existing set of Validators on FormControl? I want to add as an array. The following answer will only set them all at once .

In Angular, how to add Validator to FormControl after control is created?

Angular - Dynamically add/remove validators

newFormControl.setValidators([Validators.required])
newFormControl.setValidators([Validators.pattern("^[0-9]*$")])
newFormControl.setValidators([Validators.maxLength])

2 Answers2

0

The setValidators() REMOVES the previous validators, so you may want to collect your validators separately, and for example keep them in two variables, and set them with one setValidators() as needed.


    const validators1 = [Validators.required, Validators.pattern("^[0-9]*$"), Validators.maxLength(10)])]
    const validators2 = [Validators.required]

    if( if_you_want_all_three_validators ){
        newFormControl.setValidators(validators1)
    } else {
        // by default you want only one validator:
        newFormControl.setValidators(validators2)
    }

So this way you do not need to set them one by one.

(As the validators are not stored in an array indside setValidators(), you have to send all the validators into setValidators with only one call.)

  • I know thats, thats what I'm trying to, how do I set them cumulatively? didn't answer my question yet, thanks –  Nov 26 '20 at 08:26
  • Unfortunately you may not set them cumulatively, because setValidators() generates a NEW FUNCTION every time it has been called. So, when you call the setValidators(), the old validators are not available anymore. Maybe there is a hack to grab the old validator function, and use that with the new validators, but that would lead to an extremely long validator function chain... and probably stack error. – György Szy Nov 26 '20 at 08:40
  • (also note maxLength needs a parameter) – György Szy Nov 26 '20 at 08:45
  • hi, is there anyway to initialize an array and push them all at once? Would this work? let test = new Array(); test.push(Validators.required) test.push(Validators.minLength(10)) test.push(Validators.maxLength(10)), test.push(Validators.pattern("^[0-9]*$")) I will test this? –  Nov 26 '20 at 08:48
  • feel free to test, and I can send points, it seems to be working for me, thanks ! –  Nov 26 '20 at 08:48
0

You can set an array with new Array<ValidatorFn>();, and push validators below individually.

let validatorList = new Array<ValidatorFn>();
validatorList.push(Validators.required);
validatorList.push(Validators.pattern("^[0-9]*$"));
validatorList.push(Validators.maxLength(item.characterLimit));
newForm.addControl('test', new FormControl(d'5', validatorList));