0

I have a Validators.pattern for a field, and that's the only validation I have on my form.

Normal usage is working. It validates the field properly however the issue occurs when you try to copy and paste.

If you copy and paste on the field repeatedly on the field, it is like the validity of the field is being toggled( submit button is disabled if form is invalid )

Issue also occurs when I populate a the data from other source like search or auto-suggest.

buildForm(obj) {
  this.form = this.fb.group({
    field: [obj['field'] || '', Validators.pattern(/MY_REG_EX_HERE/g)],
    id: [obj['id'] || ''],
  });  
}
2
  • Could you give some code example ? Commented Aug 28, 2018 at 11:58
  • updated the question Commented Aug 28, 2018 at 13:14

2 Answers 2

1

I am not really sure about the main cause of the issue but as a workaround, I created custom validator with same REGEX. I will post it here and might help someone.

import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

export function customValidator(control: AbstractControl) {
    if (control.value !== '') {
      const isValid = (/MY_REG_EX_HERE/g).test(control.value)
      return isValid ? null : { customValidator: true };
    } else {
      return null;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I had a similar problem. I studied it in detail and found out the reason. Like me, you are using the /g modifier. which has a side effect if the regex is assigned to a variable. This modifier indicates the continuation of the search in the string. To understand the "unexpected" behavior, take a look at the screenshot.
RegExp test with variable
You can find out more information here

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.