Home > Net >  How to handle special cases in Angular Form Validation?
How to handle special cases in Angular Form Validation?

Time:03-19

I have a phone field where two formats are valid - "123-456-7890" and " 01 123-456-7890". I have a pattern to handle the second case Validators.pattern(/(\ \d{2})?\d{3}[\-]?\d{3}[\-]?\d{4}/) but how to make the first case also acceptable? As far as I can tell from the docs, the Validators only support && conditions, but not || conditions. Am I missing something?

Also, I'd like to make the field turn red as stuff is being entered into it if it has not yet met the validation criteria, and not annoy the user with popups along the way. Then when he leaves the field, it stays red. Then only when the form is submitted does it list all the fields that are wrong. Is there a way to do that?

CodePudding user response:

Updating regex to /^(\ ?\d{2}\s)?\d{3}[\-]?\d{3}[\-]?\d{4}$/ will work, and if you want a space to be optional after country code use this /^(\ ?\d{2}\s?)?\d{3}[\-]?\d{3}[\-]?\d{4}$/.

  • Related