开发者

How to write this regexp?

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<2开发者_运维问答1 && nr!=''){

 }

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

Thanks


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜