Validating Phone Numbers Using Javascript

大憨熊 提交于 2019-12-19 03:24:40

问题


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.

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:

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:

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

JSFiddle:

http://jsfiddle.net/mkdsjc0p/


回答1:


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

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.




回答2:


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




回答3:


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/




回答4:


<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>



回答5:


<!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>



回答6:


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

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



回答7:


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

^(([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.




回答8:


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;
}


来源:https://stackoverflow.com/questions/26211225/validating-phone-numbers-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!