16

i'm tring to add validator to FormContol dynamic (not on initialization) and it's not work....

the code:

this.formGroup.controls["firstName"].validator = Validators.Required;

Did anyone do it?

4 Answers 4

41

Try this, it should work

this.formGroup.controls["firstName"].setValidators(Validators.required);

For multiple validators

this.formGroup.controls["firstName"].setValidators([Validators.required, Validators.minLength(2)]);

But doing so will override any validators that are provided during initialization

EDIT :

To reflect the form controls with newly added Validators immediately, we have to call this.formGroup.controls["firstName"].updateValueAndValidity(); after setting validators dynamically.

this.formGroup.controls["firstName"].setValidators(Validators.required);
this.formGroup.controls["firstName"].updateValueAndValidity();

DEMO for the same

* NOTE *

updateValueAndValidity() will trigger a valueChanges event even if the value didn't really change (potentially resulting in an infinite loop, if you're calling it from within a valueChanges subscription). You can prevent that by using the optional parameter object: { onlySelf: true, emitEvent: false}

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

Comments

6

While Amit Chigadani's answer is correct, please bear in mind the following.

While this solution works for updating validators, the new validators themselves will not be run, until you change the form fields value. it is thus recommended to run the following function straight after you update you validators ;)

In laymans terms: Add the line, If you want your ng-valid and ng-invalid classes to update themselves.

this.formGroup.controls["firstName"].setValidators([Validators.required, Validators.minLength(2)]);
this.formGroup.controls["firstName"].updateValueAndValidity();

In case you only want to update the value and validity of this single control, then add this option

this.formGroup.controls["firstName"].setValidators([Validators.required, Validators.minLength(2)]);
this.formGroup.controls["firstName"].updateValueAndValidity({onlySelf: true});

Another sidenote. In Angular2, one shouldn't use the array syntax to get form group controls, but this

this.formGroup.get("firstName");

Which also accepts the dot notation

this.formGroup.get("userSectionFormGroup.firstName");

2 Comments

Thanks, man!! I was so angry that my submit wouldn't disable after adding a required validation! And it wouldn't enable after removing it!
Glad to help :)
3

got the solution we can do with the below code.

const validators = new Array<Validators>();
          validations.forEach(validation => {
            switch (validation.Type) {
              case 'required':
                validators.push(Validators.required);
                break;
              case 'minLength':
                validators.push(Validators.minLength(parseInt(validation.Expression, 10)));
                break;
              case 'maxLength':
                validators.push(Validators.maxLength(parseInt(validation.Expression, 10)));
                break;
              case 'pattern':
                validators.push(Validators.pattern(validation.Expression));
                break;
            }
          });
          this.form.controls[i].setValidators(validators);
 }
      }
    });

2 Comments

Very usefull the "pattern" and "max/minLength" example, using ".Expression"! Thanks!
Btw, "validators" Type should be "ValidatorFn" and not "Validators". ;-) At least in Angular V6 - don't know on previous ones, if Validators were already functions...
1

I ended up using:

export function getValidatorFnArray(obj): ValidatorFn[] {

  const validators = [];

  if (obj.required || obj.required === '' ) {
    validators.push(Validators.required);
  }
  if (obj.minLength) {
    validators.push(Validators.minLength(parseInt(obj.minLength, 10)));
  }
  if (obj.maxLength) {
    validators.push(Validators.maxLength(parseInt(obj.maxLength, 10)));
  }
  if (obj.pattern) {
    validators.push(Validators.pattern(obj.pattern));
  }
  if (obj.email || obj.email === '') {
    validators.push(Validators.email);
  }

  return validators
}

where obj could be something like:

validation: { 
  required: '',
  pattern: '\d+',
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.