View Full Version : Regular Expressions!
Just trying to get a page up so I can send texts to my mobile from online. I want to validate the senders mobile number, and to do this I can use a regular expression.
The number has to start with '07' and be 11 chars long.
"07([0-9]){9,9}" works fine for this.
I also want users to be able to leave it blank so it returns null or an empty string, I can't work out how to test for empty strings!
I've tried:
07([0-9]){9,9}|[]
07([0-9]){9,9}|[a]
07([0-9]){9,9}|[0]
07([0-9]){9,9}|[^A-Za-z0-9]
07([0-9]){9,9}|[?!^A-Za-z0-9]
or ones similar to those & a lot of others!
Can anyone help!
Thanks,
A
AlastairM
11-04-2003, 16:25
07([0-9]){9,9}|(^$)
seems to work for me ;)
basically your looking for either a tch or the start of the string immediatley followed by the end of the string.
You could of course test the lengh of the string before you use the regular expression eg.
if emptystring then
do something
else
do regexp
end if
Gotta love regexp's tho...
cheers
alastair
Thanks for that, just had time to test it and works great!
Couldn't test the length before using the regexp as working on a site, easier for me to just client validate first rather than submit and validate.
Thanks again,
A
A quick note on the use of {} in perl regexs. The following variants exist (n and m being integers):
{m} = match exactly m times
{m,} = match m or more times
{m,n} = match a minimum of m and a maximum of n times
So for your mobile number checking regex {9,9} is unnecessary overkill - {9} will do just the same job and will be faster to execute as the regex engine will effectively do:
if(characterCount == m) { passed! }
rather than
if(characterCount >= m && characterCount <= n) { passed!}
of course if m and n are the same the second conditional statement is just wasting time. This is an irrelevant time saving if you're just checking the occasional mobile number but is worth bearing in mind if you try anything a bit more complex.
Burgi
When i use regexp's to validate phone numbers i run two passes.
pass 1 removes all non numeric characters (spaces, brackets etc.) except for the + symbol and stores the result as a string. I do this because some people add +44 to their numbers, others use spaces / brackets between the dial/area code and number.
something like this will remove any unrequired characaterse:
[^\d\+]
Pass 2 then performs the regexp match your trying to run returning true if the number is valid and false if its not.
I use something like for my test:
(?:\+\d{2})*07\d{9}
I use Javascript so my code looks like this:
var MobileNo="+44 0797 1234567"
var TidyMobileNo = MobileNo.replace(/[^\d\+]/g, "")
var ValidNubmer = TidyMobileNo.match(/(?:\+\d{2})*07\d{9}/)
if (ValidNubmer)
... do stuff
vBulletin® v3.7.1, Copyright ©2000-2008, Jelsoft Enterprises Ltd.