If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Enjoy an ad free experience by logging in. Not a member yet? Register.

constructing a dynamic regex

so here's the thing: I'm trying to write a code that dynamically constructs regexes to validate phone numbers depending on user input. there can be any number of formats, but the numbers will always be separated by hyphens. The user gets to choose the format, then later the validation runs according to what they have chosen.

Thus:

345-345435 could be valid
as could
2-44444444-44

But I have been finding that constructing the regexes dynamically slows the code down noticeably. For example, if they're hardcoded like this:

it slows it waaaay down, taking about a second longer to run the validation code.

the only real difference that I can see is the use of the new RegExp constructor, but I'm assuming I have to use that because otherwise it's just a string. I even tried the dreaded eval(), but got the same results.

because the validation has to follow the rules that the user dictates, so if they say for example that formats
XXX-XXXX
and
XX-XXXX-XXX

are valid, if they try to enter 22-343 it should fail validation

I am sure that you know what you are doing, but IMO excessive validation of telephone number formats is pointess when the user can simply make a mistake and enter his number wrongly, say with transposed digits. I would have thought that it would be enough to check for just digits and hyphens/spaces.

Surely there are only a limited number of valid formats?

Last edited by Philip M; 01-22-2013 at 07:50 AM.

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.

ha, ha. I wish I shared your confidence. Unfortunately, the formats range wildly, depending on which country the user is in - an Argentine cell phone could be:
XX-XXXXXX or XX-XXX-XXXX or XX-XXXX-XXXX

while a Vanuatu landline could be XX-XXX

but you don't want an Argentine cell phone number to validate according to Vanuatu landline rules just because the user forgot a few digits, if you follow my thinking.

Anyway. It's sorted now, but thanks for your input.

Surely it is up to the user to enter his telephone number correctly? Nothing will prevent digit transpositions etc. Likewise his email address. And indeed his name.

In any case I never reveal my telepone number which is ex-directory. If a number is required in a form I just invent one such as 0207 270 3000 (which is David Cameron 10 Downing Street). Then he can deal with all the calls about ***** enlargement.

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.