【问题标题】:Validating Phone Numbers Using Javascript使用 Javascript 验证电话号码
【发布时间】:2014-11-30 10:00:55
【问题描述】:

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

我无法让它正常工作。我尝试了几种不同的方法来做到这一点,但得到了几种不同类型的错误。一种方法似乎可行,但红色边框只显示一秒钟然后消失,并且文本框中的值被重置。

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

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/

【问题讨论】:

  • 您将phone 设置为元素value 属性,然后在测试中,您再次访问value 属性,这一次是您已经获得的值,这不会'不存在。
  • 您已经将表单控件引用为phone,为什么还要使用document.getElementById?而不是match,你应该使用test
  • 这不是引用问题的欺骗,因为“什么是电话号码”的标准不同。参考问题中提出的解决方案不符合此处的要求。

标签: javascript html validation phone-number


【解决方案1】:

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

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

但总的来说,这种假设是不正确的,因为人们可能会输入类似 ++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;  }

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

【讨论】:

    【解决方案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");

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

    【讨论】:

    • 这是最好的!
    【解决方案3】:

    试试这个 我它正在工作。

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

        看到太多边缘情况,我进行了更简单的检查:

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

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

        【讨论】:

          【解决方案6】:

          在 java 脚本中使用正则表达式验证电话号码。

          在印度,电话是 10 位数字,起始数字是 6、7、8 和 9。

          Javascript 和 HTML 代码:

          function validate()
          {
            var text = document.getElementById("pno").value;
            var regx = /^[6-9]\d{9}$/ ;
            if(regx.test(text))
              alert("valid");
            else
              alert("invalid");
          }
          <html>
              <head>
                  <title>JS compiler - knox97</title>
            </head>
            <body>
            <input id="pno" placeholder="phonenumber" type="tel" maxlength="10" > 
              </br></br>
              <button onclick="validate()" type="button">submit</button>
            </body>
          </html>

          【讨论】:

            【解决方案7】:
            <!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>
            

            【讨论】:

            • 您可以在答案中添加详细信息吗?
            【解决方案8】:

            HTML

                    <input type='text' onChange={phonNumValidation(e)} 
                     placeholder='Enter phone number...' id='phone_num' />
            

            JAVASCRIPT

            它只允许数字, 它不允许 + 符号和 e, 还有字符串和正则表达式

                phonNumValidation = (e)=>{
                    e.target.value = e.target.value.replace(/[^0-9 ]/g, "").replace(" ","")
                }
            

            【讨论】:

              【解决方案9】:
              <!DOCTYPE html>
              <html>
                  <head>
                      <style>
                         .container__1{
                             max-width: 450px;
                             font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
                         }
                         .container__1 label{
                             display: block;
                             margin-bottom: 10px;
                         }
                         .container__1 label > span{
                             float: left;
                             width: 100px;
                             color: #F072A9;
                             font-weight: bold;
                             font-size: 13px;
                             text-shadow: 1px 1px 1px #fff;
                         }
                         .container__1 fieldset{
                             border-radius: 10px;
                             -webkit-border-radious:10px;
                             -moz-border-radoius: 10px;
                             margin: 0px 0px 0px 0px;
                             border: 1px solid #FFD2D2;
                             padding: 20px;
                             background:#FFF4F4 ;
                             box-shadow: inset 0px 0px 15px #FFE5E5;
              
              
                         }
                         .container__1 fieldset legend{
                             color: #FFA0C9;
                             border-top: 1px solid #FFD2D2 ;
                             border-left: 1px solid #FFD2D2 ;
                             border-right: 1px solid #FFD2D2 ;
                             border-radius: 5px 5px 0px 0px;
                             background: #FFF4F4;
                             padding: 0px 8px 3px 8px;
                             box-shadow: -0px -1px 2px #F1F1F1;
                             font-weight: normal;
                             font-size: 12px;
                         }
                         .container__1 textarea{
                             width: 250px;
                             height: 100px;
                         }.container__1 input[type=text],
                         .container__1 input[type=email],
                         .container__1 select{
                             border-radius: 3px;
                             border: 1px solid #FFC2DC;
                             outline: none;
                             color: #F072A9;
                             padding: 5px 8px 5px 8px;
                             box-shadow: inset 1px 1px 4px #FFD5E7;
                             background: #FFEFF6;
                             
              
                         }
                         .container__1 input[type=submit],
                         .container__1 input[type=button]{
                             background: #EB3B88;
                             border: 1px solid #C94A81;
                             padding: 5px 15px 5px 15px;
                             color: #FFCBE2;
                             box-shadow: inset -1px -1px 3px #FF62A7;
                             border-radius: 3px;
                             font-weight: bold;
                         }
                         .required{
                             color: red;
                         }
                      </style>
                  </head>
                  <body>
                      <div class="container__1">
                          <form name="RegisterForm" onsubmit="return(SubmitClick())">
                              <fieldset>
                                  <legend>Personal</legend>
                                  <label for="field1"><span >Name<span class="required">*</span><input id="name" type="text" class="input-field" name="Name" value=""</label>
                                  <label for="field2"><span >Email<span class="required">*</span><input placeholder="Ex: csa123@yahoo.in" id="email" type="email" class="input-field" name="Email" value=""</label>
                                  <label for="field3"><span >Phone<span class="required">*</span><input placeholder="+919853004369" id="mobile" type="text" class="input-field" name="Mobile" value=""</label>
                                  <label for="field4">
                                      <span>Subject</span>
                                      <select name="subject" id="subject" class="select-field">
                                          <option value="none">Choose Your Sub..</option>
                                          <option value="Appointment">Appiontment</option>
                                          <option value="Interview">Interview</option>
                                          <option value="Regarding a post">Regarding a post</option>
                                      </select>
                                  </label>
                                  <label><span></span><input type="submit"  ></label>
                              </fieldset>
                          </form>
                      </div>
                  </body>
                  <script>
                      function SubmitClick(){
                      _name = document.querySelector('#name').value;
                      _email = document.querySelector('#email').value;
                      _mobile = document.querySelector('#mobile').value;
                      _subject = document.querySelector('#subject').value;
                        if(_name == '' || _name == null ){
                            alert('Enter Your Name');
                            document.RegisterForm.Name.focus();
                            return false; 
                        } 
                        var atPos = _email.indexOf('@');
                       var dotPos = _email.lastIndexOf('.');
              
                        if(_email == '' || atPos<1 || (dotPos - atPos)<2){
                            alert('Provide Your Correct Email address');
                            document.RegisterForm.Email.focus();
                            return false;
                        }
                        var regExp = /^\+91[0-9]{10}$/;
                        if(_mobile == '' || !regExp.test(_mobile)){
                            alert('Please Provide your Mobile number as Ex:- +919853004369');
                            document.RegisterForm.Mobile.focus();
                            return false;
                        }
                        if(_subject == 'none'){
                            alert('Please choose a subject');
                            document.RegisterForm.subject.focus();
                            return false;
                        }else{
                          alert (`success!!!:--'\n'Name:${_name},'\n' Mobile: ${_mobile},'\n' Email:${_email},'\n' Subject:${_subject},`)
                        }
                      
                        
                      }
                  </script>
              </html>
              

              【讨论】:

              • 虽然此代码可以解决 OP 的问题,但最好包含关于您的代码如何解决 OP 问题的说明。通过这种方式,未来的访问者可以从您的帖子中学习,并将其应用到他们自己的代码中。 SO 不是编码服务,而是知识资源。此外,高质量、完整的答案更有可能得到支持。这些功能,以及所有帖子都是独立的要求,是 SO 作为一个平台的一些优势,使其与论坛区分开来。您可以编辑以添加其他信息和/或使用源文档补充您的解释。
              【解决方案10】:
              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;
              }
              

              【讨论】:

              • 请解释一下这段代码如何/为什么解决问题。
              • 欢迎来到 Stackoverflow。如果您签出How to Answer 页面以备将来在堆栈溢出时的努力会更好。 -谢谢
              猜你喜欢
              • 2011-05-19
              • 2013-08-24
              • 1970-01-01
              • 2011-09-05
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多