使用javascript验证电话号码 [英] Validate phone number using javascript

查看:129
本文介绍了使用javascript验证电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证电话号码,例如 123-345-3456 (078)789-8908 使用JavaScript。
这是我的代码

I'm trying to validate phone number such as 123-345-3456 and (078)789-8908 using JavaScript. Here is my code

function ValidateUSPhoneNumber(phoneNumber) {
  var regExp = /^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}/;
  var phone = phoneNumber.match(regExp);
  if (phone) {
    alert('yes');
    return true;
  }
  alert('no');
  return false;
}

我正在使用验证函数ValidateUSPhoneNumber(' 123-345-34567')在最后一个连字符前有5位数,根据正则表达式无效。但该函数返回true。
任何人都可以解释原因吗?

I'm testing the function using ValidateUSPhoneNumber('123-345-34567') which has 5 digits before the last hyphen which is invalid as per regex. But the function returns true. Can any one explain why?

推荐答案

JavaScript验证电话号码:

JavaScript to validate the phone number:

function phonenumber(inputtxt) {
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  if(inputtxt.value.match(phoneno)) {
    return true;
  }
  else {
    alert("message");
    return false;
  }
}

以上脚本匹配:

XXX-XXX-XXXX

XXX.XXX.XXXX

XXX XXX XXXX

XXX-XXX-XXXX
XXX.XXX.XXXX
XXX XXX XXXX

如果您想在以下方式使用号码之前的+号:
+ XX-XXXX-XXXX
+ XX.XXXX.XXXX

+ XX XXXX XXXX
使用以下代码:

If you want to use a + sign before the number in the following way
+XX-XXXX-XXXX
+XX.XXXX.XXXX
+XX XXXX XXXX
use the following code:

function phonenumber(inputtxt) {
  var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
  if(inputtxt.value.match(phoneno)) {
    return true;
  }  
  else {  
    alert("message");
    return false;
  }
}

这篇关于使用javascript验证电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆