here's my regex in Node:
/(0|\+98)?9[0|1|2|3|4|9][0-9]{8}$/g
here's my matching criteria in logical terms:
phoneNumber = ABCD where: A: country code (+98) || leading 0 B: must be a 9 C: must be a 0, 1, 2, 3, 4 or 9 D: eight digits from [0-9]
Here's the problem
When I test a number which has a C component equal to 9, a strange thing happens, for example:
099012345678 qualifies as a valid number when it shouldn't (STRANGE)
0990123456 shouldn't qualify as a valid number and it doesn't (LOGICAL)
09901234567 should qualify as a valid number and it does (LOGICAL)
09901234567{..} do not qualify as valid and they shouldn't. (LOGICAL)
I've tested this using Node.JS v7.2.0 and v6.10.3 on macOS 10.12.4 and on Ubuntu 16.04.2
Every other test yields correct results:
090x.., 091x.., 092x.., 093x.., 094x.. --> MATCH (CORRECT)
+9891x.. --> MATCH (CORRECT)
095x.., 08xx.., --> NO MATCH (CORRECT)
091212345678 --> NO MATCH (CORRECT)
0912123456 --> NO MATCH (CORRECT)
etc ...
I suspect the strange behavior has to do with two 9's repeating; I played around with my regex for a couple of hours and finally gave up. Hoping someone could see the problem with my regex or point out a possible bug in Node's regex...
Here are some variations that I've tried without any luck
/(0|\+98)?(9[0|1|2|3|4] | 99)[0-9]{8}$/g
/(0|\+98)?(9[0|1|2|3|4|9])\d{8}$/g
/(0|\+98)?(90|91|92|93|94|99)[0-9]{8}$/g
/(0|\+98)?9(?=[0|1|2|3|4|9])[0|1|2|3|4|9][0-9]{8}$/g
SOLUTION
By the time I got the above writing finished and had a few more go's at it, realized I mistyped a question mark and my eyes could not see it even though I was staring at it the whole time with my eyes wide shut!
In conclusion:
Instead of this with an extra '?' before 9[0|1|2.. ,
/(0|\+98)?9[0|1|2|3|4|9][0-9]{8}$/g
The solution is the following:
/(0|\+98)9[0|1|2|3|4|9][0-9]{8}$/g
hope this helps out with a similar problem or gives you a working regex for Iran mobile numbers.
Just remember to trim the text if you are capturing it in an input field, and replace "-", " ", "(", ")" with "" before testing it with the regex. so that 0912 123 4567, 0912-123-4567 and (0912)123-4567 don't bug you.
via Faraz Soroush
No comments:
Post a Comment