使用 Javascript 验证电话号码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26211225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:31:56  来源:igfitidea点击:

Validating Phone Numbers Using Javascript

javascripthtmlvalidationphone-number

提问by Frawel

I'm working on a web form with several fields and a submit button. When the button is clicked, I have to verify that the required text boxes have been filled in and that the phone number is in the correct format. I can only accept 7 or 10 digit phone numbers, but characters such as (,), (-), etc are acceptable. If this box is empty or the phone number isn't in the correct format (not 7 or 10 numbers long, not a number) or has been left blank, I have to add a red border around the text box. This border is supposed to remain in place until the user corrects the error.

我正在处理一个包含多个字段和一个提交按钮的 Web 表单。单击按钮时,我必须验证所需的文本框是否已填写以及电话号码格式是否正确。我只能接受 7 位或 10 位电话号码,但可以接受 (,)、(-) 等字符。如果此框为空或电话号码格式不正确(不是 7 或 10 个数字,不是数字)或已留空,我必须在文本框周围添加红色边框。该边界应该保持原位,直到用户纠正错误。

I can't get this to work properly. I have tried several different ways to go about doing this, but have gotten several different types of errors. One way seemed to work, but the red border only displayed for a second and then disappeared and the value in the textbox was reset.

我无法让它正常工作。我尝试了几种不同的方法来执行此操作,但遇到了几种不同类型的错误。一种方法似乎有效,但红色边框只显示一秒钟,然后消失,文本框中的值被重置。

Here is my code and a link to a jsfiddle I've created:

这是我的代码和我创建的 jsfiddle 的链接:

Javascript:

Javascript:

<script type="text/javascript">
    function validateForm() {
        return checkPhone();
    }
    function checkPhone() {
        var phone = document.forms["myForm"]["phone"].value;
        var phoneNum = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; 
            if(phone.value.match(phoneNum)) {
                return true;
            }
            else {
                document.getElementById("phone").className = document.getElementById("phone").className + " error";
                return false;
            }
        }
</script>

HTML:

HTML:

<form name="myForm" onsubmit = "return validateForm()">
    Phone Number: <input type="text" id="phone"><br>
</form>

JSFiddle:

JSFiddle:

http://jsfiddle.net/mkdsjc0p/

http://jsfiddle.net/mkdsjc0p/

回答by i100

As for your regexp I guess it should be

至于你的正则表达式,我想应该是

^\+{0,2}([\-\. ])?(\(?\d{0,3}\))?([\-\. ])?\(?\d{0,3}\)?([\-\. ])?\d{3}([\-\. ])?\d{4}

But in general the presumption is not correct because one might enter something like ++44 20 1234 56789 or +44 (0) 1234 567890 it is better to do something like this

但总的来说,这个假设是不正确的,因为人们可能会输入诸如 ++44 20 1234 56789 或 +44 (0) 1234 567890 之类的东西,最好这样做

var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {  return true;  }

this will assure that entered value has 7 to 10 figures nevertheless what the formatting is. But you have to think about max length for number might be more than 10 as in the sample above.

这将确保输入的值有 7 到 10 个数字,但格式是什么。但是您必须考虑数字的最大长度可能超过 10,如上例所示。

回答by Frawel

function telephoneCheck(str) {
  var a = /^(1\s|1|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3})(\-|\s)?(\d{4})$/.test(str);
  alert(a);
}
telephoneCheck("(555) 555-5555");

Where str could be any of these formats:555-555-5555 (555)555-5555 (555) 555-5555 555 555 5555 5555555555 1 555 555 5555

其中 str 可以是以下任何一种格式:555-555-5555 (555)555-5555 (555) 555-5555 555 555 5555 5555555555 1 555 555 5555

回答by Guljar Prasad

Try this I It's working.

试试这个我正在工作。

<form>
<input type="text" name="mobile" pattern="[1-9]{1}[0-9]{9}" title="Enter 10 digit mobile number" placeholder="Mobile number" required>
<button>
Save
</button>
</form>
 

https://jsfiddle.net/guljarpd/12b7v330/

https://jsfiddle.net/guljarpd/12b7v330/

回答by Sachin Gupta

<html>
<title>Practice Session</title>
<body>           
<form name="RegForm" onsubmit="return validate()" method="post">  
<p>Name: <input type="text" name="Name"> </p><br>        
<p>Contact: <input type="text" name="Telephone"> </p><br>   
<p><input type="submit" value="send" name="Submit"></p>          
</form> 
</body>
<script> 
function validate()                                    
{ 
var name = document.forms["RegForm"]["Name"];                
var phone = document.forms["RegForm"]["Telephone"];  
if (name.value == "")                                  
{ 
window.alert("Please enter your name."); 
name.focus();
return false;
}
else if(isNaN(name.value) /*"%d[10]"*/)
{
alert("name confirmed");
}
else{ 
window.alert("please enter character"); 
}   
if (phone.value == "")                           
{ 
window.alert("Please enter your telephone number."); 
phone.focus();
return false; 
} 
else if(!isNaN(phone.value) /*phone.value == isNaN(phone.value)*/)
{
alert("number confirmed");
}
else{
window.alert("please enter numbers only");
}   
}
</script> 
</html>

回答by Codemaker

You can refer the following site to know about phone number validation

您可以参考以下网站了解电话号码验证

https://www.w3resource.com/javascript/form/non-empty-field.php

回答by Sahil Ahuja

Having seem simply too many edge cases, I went for a simpler check:

似乎有太多的边缘情况,我进行了一个更简单的检查:

^(([0-9\ \+\_\-\,\.\^\*\?\$\^\#\(\)])|(ext|x)){1,20}$

^(([0-9\ \+\_\-\,\.\^\*\?\$\^\#\(\)])|(ext|x)){1,20}$

The first thing one may point out is allowing repetition of "ext", but the purpose of this regex is to prevent users from accidentally entering email ids etc. instead of phone numbers, which it does.

可能要指出的第一件事是允许重复“ext”,但此正则表达式的目的是防止用户意外输入电子邮件 ID 等而不是电话号码,它确实做到了。

回答by vishwanath

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="../Homepage-30-06-2016/Css.css" >
<title>Form</title>

<script type="text/javascript">

        function isChar(evt) {
            evt = (evt) ? evt : window.event;
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (charCode > 47 && charCode < 58) {

                document.getElementById("error").innerHTML = "*Please Enter Your Name Only";
                document.getElementById("fullname").focus();
                document.getElementById("fullname").style.borderColor = 'red';
                return false;
            }
            else {
                document.getElementById("error").innerHTML = "";
                document.getElementById("fullname").style.borderColor = '';

                return true;
            }
        }
</script>
</head>

<body>

        <h1 style="margin-left:20px;"Registration Form>Registration Form</h1><hr/>

           Name: <input id="fullname" type="text" placeholder="Full Name*"
                 name="fullname" onKeyPress="return isChar(event)" onChange="return isChar(event);"/><label id="error"></label><br /><br />

<button type="submit" id="submit" name="submit" onClick="return valid(event)" class="btn btn-link text-uppercase"> Submit now</button>

回答by subi

if (charCode > 47 && charCode < 58) {
    document.getElementById("error").innerHTML = "*Please Enter Your Name Only";
    document.getElementById("fullname").focus();
    document.getElementById("fullname").style.borderColor = 'red';
    return false;
} else {
    document.getElementById("error").innerHTML = "";
    document.getElementById("fullname").style.borderColor = '';
    return true;
}