h1ghland3r
h1ghland3r

Reputation: 136

Angular issue in validators.pattern when added dynamically

I am with an issue with the validators.pattern using reactive form. If I add the validation in the formbuilder group, it works just fine, which is saying the field is invalid when the regex pattern is not met. But when I add the validation dynamically at the moment of the submit, if I input a value in the wrong pattern, it says the input is valid, and when I add a value in the correct pattern, it says is invalid. o_O

  1. Validator in Form Builder
  form = this.formBuilder.group({
    field: [null, Validators.pattern('^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$')]
  });
  1. Validator added dynamically:
this.form.controls[field].setValidators([Validators.pattern('/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/')]);
this.form.controls[field].updateValueAndValidity();

The only difference I found is because I need to add the / in the second method. If I remove the /, the validator doesn't work.

I also tried this.form.get('field').setValidators... but the behavior was the same.

Do you guys know what I am doing wrong?

Thanks!

Upvotes: 0

Views: 1049

Answers (1)

Related Questions