0

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!

1 Answer 1

1

It is simply failing. Please, take a look at this: https://github.com/angular/angular/blob/2ab8e88924532ecd8a3459b8cb11b4ce9b7f847b/packages/forms/src/validators.ts#L349-L406.

Angular prepends ^ and $ to your string if you passed in a string anyway. Your string is simply failing. https://github.com/angular/angular/blob/2ab8e88924532ecd8a3459b8cb11b4ce9b7f847b/packages/forms/src/validators.ts#L387 and https://github.com/angular/angular/blob/2ab8e88924532ecd8a3459b8cb11b4ce9b7f847b/packages/forms/src/validators.ts#L391

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

Comments

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.