I have this regex of mine that will validate phone number (i.e. 1 (417) 230-0718). Using this regex /^[\ ]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im
, I've encountered and error while running my test cases in next about Unnecessary escape character: . How to disable this eslint-error in order for me to proceed with my test case and use the regex.
Appreciate for any help!
CodePudding user response:
Your example phone number does not match your original regex and that contains multiple unnecessary escapes.
To answer your initial question first: in a []
part, you don't need to escape characters - the only character with a special meaning is the ^
, and that also only has a special meaning as the first character inside []
so you can put it further back. Also you don't need []
for only one character - then the escaped version is better.
Next to your regex not matching your example phone number: You are missing the international prefix after the sign in the beginning.
I would rewrite your regex to the following:
/^(?:\ \d{1,3}[-\s.]?)?\(?[0-9]{3}\)?[-\s.]?[0-9]{3}[-\s.]?[0-9]{4,6}$/m
You don't need the i flag as there are no upper/lower case digits.
This updated regex allows for an optional 1 to 3 digit international prefix, but that has to be preceded with a
CodePudding user response:
It is correct way for this issue.
/^[ ]?[(]?[0-9]{3}[)]?[-\s.]?[0-9]{3}[-\s.]?[0-9]{4,6}$/im