Reputation: 2973
I am using the \+\d{1,4}\s?-\s?(?!0)\d{1,10}\b
to execute the below test cases
1 - There should be at max 4 digits in between + and - .
2 - Phone number shall be a combination of +,- and digits
3 - 0 shall not be allowed after -
4 - After - only 10 digits are allowed
5 - Space allowed after and before -
E.g
1 - +91234-1234567 - Fail (1st Condition fails)
2 - +123-1234567 - Pass
3 - + - Fail (2nd condition fails)
4 - - - Fail (2nd condition fails)
5 - 91234545555 - Fail (2nd condition fails)
6 - +21-012345 - Fail (3rd Condition fails)
7 - +91-12345678910 - Fail (4th condition fails)
8 - +32 - 12345678 - Pass (Space allowed before and after -)
Now i want to make some part ( Country code +91- ) as optional to execute the below test cases
E.g.
1)12345678 - Pass (Since we are making country code(+91-) as optional)
2)+1233433 - Fail
3)+91-1233333- pass
To achive this i did the following changes in the regex /(\+\d{1,4}\s?-\s?)?(?!0)\d{1,10}\b/
but with the above updated regex its allowing the following also
1)-123455
2)+123333
I want to make the whole thing as optional (+XX-) not the part of it . Please help me in it . Thanks in advance.
Upvotes: 2
Views: 387
Reputation: 15415
/^(?:\+\d{1,4}\s?-\s?)?(?!0)\d{1,10}\b/
Breakdown:
^ Assert at beginning of string
(?:\+\d{1,4}\s?-\s?)? Only changed to group country code
and make it match 0 - 1 times.
and the rest Otherwise no changes.
The key changes are the string boundary assertion and the optional country code group.
Upvotes: 1