views:

46

answers:

2

I am validating a field which may NOT be anything but numbers, but may include a space or a minus-sign.

This is for validating phone number field! So, these criterias should be met: (might have forgot a criteria, if so remind me)

 1- Atleast 5 numbers
 2- May contain space
 3- Not shorter than 5 characters
 4- Not longer than 20 characters
 5- May contain minus-sign
 6- Not empty

 if (nr.length>4 && nr.length<21 && nr!=''){

 }

How should I write the regexp? Or the if statement?

Thanks

+4  A: 

Try this regular expression:

^(?=(?:\D*\d){5})[\d -]{5,20}$

The lookahead assertion (?=(?:\D*\d){5}) tests for the five digits. The rest tests the length of at least 5 and at most 20 characters that can only be digits, the space or hyphen character.

Gumbo
Are you not missing the minus sign?
Vinko Vrsalovic
minus sign???...
Camran
+1  A: 

The nr != '' condition is redundant since the length comparisons already exclude a length of zero.

So with the length comparisons out of the way, it looks like you're down to a simple character class of digits, spaces, and dashes:

/[\d\s-]{5,20}/

Of course, this allows things like ----- or a bunch of spaces. So maybe you want to remove everything that's not a digit first, then just check for

/\d{5,20}/

which would probably be simpler.

friedo
+1 for beating me to it. I was just about to hit return, too! :)
Robusto