最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript regex to validate a phone number - Stack Overflow

programmeradmin2浏览0评论

I am working to modify a script. The script contains a form to allow visitors to send an SMS to phone numbers. In the form I have a text box in which users enter the phone number of the text receiver. I am using a regex to validate the phone number to prevent spammers and make sure the user typed the correct number.

Here are the default phone numbers used in Afghanistan:

+93785657024
+93795657024
+93700565656
+93775657024

The regex validation first should make sure that +93 is used, then make sure that 78, 77, 79 or 700 (one of these) is used after +93 and finally followed by 6 digits.

Here is the Javascript code I am trying to fix. This code now works only for +937 followed by 8 digits.

<script type="text/javascript">
function test (){
  var phoneRegex = new RegExp('^937\d{8}$');
  var phoneNum = document.getElementById("receiver").value;
  if(!(phoneRegex.test(phoneNum))) {
    alert("Invalid Phone Number");
    document.getElementById("receiver").focus();
  } else {
    alert("valid");
  }
}
</script>

I am working to modify a script. The script contains a form to allow visitors to send an SMS to phone numbers. In the form I have a text box in which users enter the phone number of the text receiver. I am using a regex to validate the phone number to prevent spammers and make sure the user typed the correct number.

Here are the default phone numbers used in Afghanistan:

+93785657024
+93795657024
+93700565656
+93775657024

The regex validation first should make sure that +93 is used, then make sure that 78, 77, 79 or 700 (one of these) is used after +93 and finally followed by 6 digits.

Here is the Javascript code I am trying to fix. This code now works only for +937 followed by 8 digits.

<script type="text/javascript">
function test (){
  var phoneRegex = new RegExp('^937\d{8}$');
  var phoneNum = document.getElementById("receiver").value;
  if(!(phoneRegex.test(phoneNum))) {
    alert("Invalid Phone Number");
    document.getElementById("receiver").focus();
  } else {
    alert("valid");
  }
}
</script>
Share Improve this question edited Jul 1, 2013 at 17:46 dda 6,2132 gold badges27 silver badges35 bronze badges asked Jul 1, 2013 at 17:43 Nargis AkbariNargis Akbari 151 silver badge5 bronze badges 5
  • 2 stackoverflow./q/123559 – Robert Harvey Commented Jul 1, 2013 at 17:44
  • Either /^937\d{8}$/ or new RegExp("^937\\d{8}$") – Bergi Commented Jul 1, 2013 at 17:45
  • @Bergi That would match stuff without the plus sign and binations that are not ok like 9370, 9371, 9372, 9373, 9374, 9375, 9376... – dda Commented Jul 1, 2013 at 17:53
  • you should consider input type tel bined with pattern attribute instead of JS validator – Jan Turoň Commented Jul 1, 2013 at 18:37
  • @dda, 9370 is invalid? Number is present above, isn't it? And for the plus, just add it in: new RegExp('^\+937\d{8}$'); and looks good to me. If 9371-9376 are invalid, then new RegExp('^937[0789]\d{7}$'); should work. – vapcguy Commented Aug 14, 2014 at 2:59
Add a ment  | 

4 Answers 4

Reset to default 2

The regex validation first should make sure that +93 is used, then make sure that 78, 77, 79 or 700 (one of these) is used after +93 and finally followed by 6 digits.


This answer will not work except in the 700 case because the OP specified that all prefixes were followed by 6 digits, when in fact only 93700 is followed by 6, and the other prefixes are followed by 7 digits.

/^\+93(77\d|78\d|79\d|700)\d{6}$/

should do it.

Your original regex doesn't require a "+" at the front though.

I think this would suit your condition

Totally you need 11 digits prefixed with +.

Therefore if 77|78|79 means followed by 7 digits or if 700, followed by 6 digits.

var reg = /^\+93((77|78|79)\d{7}|700\d{6})$/;
console.log(reg.test('+93705657024'));

Check this Fiddle

Regular expression itself:

var phoneRegex = new RegExp('(937(?:00\\d{6}|[789]\\d{7}))');

Notes:

  • Since you are using new RegExp, I have not inserted / and / around the expression. (I am mentioning this because you mented that some of the other answers did not work at all, and I suspect that is because you may have forgotten to remove the / and / before testing them, perhaps? There seem to be minor problems with them which is why I am also answering, but the other answers should at least match some valid phone numbers if you remove the / and / that surround the regular expressions.)
  • You seem to have made a mistake in counting the digits vs. the examples you gave of valid Afghanistan phone numbers. +9377, +9378, etc. are followed by 7 digits rather than 6, while only +93700 is actually followed by 6.
  • My expression puts the full phone number into the temporary variable $1, which can e in handy. (I used a non-capturing group for the alternatives in the second part of the match because extra captures sometimes can be a bother when I want to do something else with the results of the match. For what your code is doing, it would work the same with or without the ?: that my regular expression contains.)
  • My expression does not anchor the match to the beginning or end of the string, because doing so would return false for valid numbers that had punctuation, like the + that you showed in your own phone numbers.
  • For the same reason, I suggest that you delete non-numeric characters before checking input for a valid phone number. Right now phone numbers using parentheses or hyphens or any traditional punctuation will return false even though they are actually valid.
  • This modification of your code would work for ensuring that valid phone numbers are recognized correctly by first removing punctuation:

    if(!(phoneRegex.test(phoneNum.replace(/\D+/g, '')))) {
    
  • If you make this modification to your code, then it would be appropriate to add the anchoring expressions ^ and $ around my suggested regular expression to make sure it only contained a valid phone number, not a longer number such as a credit card number.

There is a problem with the way your code checks the results from doing the regular expression test. This code will work better for you:

<script type="text/javascript">
function test (){
  var phoneField = document.getElementById("receiver")
  var phoneNum = phoneField.value;
  if (/^(937(?:00\d{6}|[789]\d{7}))$/.test(phoneNum.replace(/\D+/g, ''))) {
  alert('valid');
  } else {
  alert('Invalid phone number');
  phoneField.focus();
  }
}
</script>
<input id="receiver" value="+93785657024" />
<input type="button" onclick="test()" value="Check this number" />

Note: I got some of my code mixed up. Please ignore my other code (the one that was uploaded to that link, I mean). This one works.

Use:

/^\+937([789]|00)\d\d\d\d\d\d$/

That should do it.

+937 All your numbers start with this
([789]|00) Either 7, 8, 9 or 00
\d\d\d\d\d 6 digits

发布评论

评论列表(0)

  1. 暂无评论