Reputation: 136
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
form = this.formBuilder.group({
field: [null, Validators.pattern('^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$')]
});
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
Reputation: 68
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
Upvotes: 1