【问题标题】:Validation for email or phone number for same text field in angularjs验证angularjs中相同文本字段的电子邮件或电话号码
【发布时间】:2015-12-22 22:22:16
【问题描述】:

我正在为我在 AngularJs 中的项目填写注册表单。用户可以使用他/她的电子邮件/电话进行注册。我需要验证那个特定的文本框。

我对两者都有验证,使用不同的文本字段,使用 ng-pattern。但是如何在一个文本字段中验证两者?

我已经更新了我的代码,在这里:- enter code here http://plnkr.co/edit/mCVxHxl2DIvqOYtVapRN?p=preview

【问题讨论】:

  • 使用将两个正则表达式与 or 组合的正则表达式:/^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,5})$|^\d+$/

标签: javascript html angularjs validation angularjs-directive


【解决方案1】:

这里是电子邮件或电话号码的正则表达式,请看一下,希望对您有所帮助。

谢谢

^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})|(^[0-9]{10})+$

这也是一个例子。

https://jsfiddle.net/sanat/b2m436L5/17/

function validate(){
    var value = $("#email_phone").val();
  
  var regex = new RegExp('^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})|(^[0-9]{10})+$');
  
  if(value){
         if(!regex.test(value)){
          $("#error").text("Please enter valid email address or phone number.")
       }else{
         $("#error").text('')
       }
  }else{
    $("#error").text('This field is required.')
  }
    

}
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
#error{
  font-size:14px;
  color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
   <div>
   <input type="text" placeholder="Email/phone" id="email_phone">
    <button onClick="validate()">Submit</button>
    
   </div>
   <span id="error"></span>
</div>

【讨论】:

    【解决方案2】:

    简单代码

    像验证一样完成工作:amazon、Facebook、uber.etc 使用单一输入的电子邮件或电话号码...

    试试它的工作原理......

          <script>
            $(document).ready(function () {
               $("#cuntryCode").hide();
                $("#useridInput").on('input', function () {
                    var len = $("#useridInput").val().length;
                    if (len >= 2) {
                        var VAL = this.value;
                        var intRegex = /^[1-9][0-9]*([.][0-9]{2}|)$/;
                        if (!intRegex.test(VAL)) {
                            $('#error-caption').html('Invalid email. Please check spelling.');
                            $('#error-caption').css('color', 'red');
                            $("#cuntryCode").hide();
                        } else {                    
                         if(len < 10){
                            $('#error-caption').html('Invalid mobile number. Please try again.');
                            $('#error-caption').css('color', 'red');
                            $("#cuntryCode").show();
                          }else{
                            $('#error-caption').html('Invalid mobile number. length must be 10 digit.');
                            $('#error-caption').css('color', 'red');
                        }
                      }
                    }else{
                       $("#cuntryCode").hide();
                       $('#error-caption').html('');
                    }
    
                });             
            });
    
        </script>
    
    
    
    <form class="push--top-small forward" method="POST" data-reactid="15">
                <h4 id="input-title" data-reactid="16">Welcome back
                </h4>
                <label class="label" id="input-label" for="useridInput" data-reactid="17">Sign in with your email address or mobile number.
                </label>
                <div style="margin-bottom:24px;" data-reactid="18">
                  <div >
                    <div id="cuntryCode" class="_style_4kEO6r" style="float: left; height: 44px; line-height: 44px;">
                      <div tabindex="0" > +241
                      </div>                      
                    </div>
                    <div style="display:flex;">
                      <input id="useridInput" autocorrect="off" autocapitalize="off" name="textInputValue" class="text-input" placeholder="Email or mobile number" aria-required="true" aria-invalid="false" aria-describedby="error-caption input-title">
                    </div>
                  </div>
                  <div id="error-caption">
                  </div>
                </div>
                <button class="btn btn--arrow btn--full" data-reactid="24">
                  <span class="push-small--right" data-reactid="25">Next
                  </span>
                </button>
              </form>
    

    【讨论】:

      【解决方案3】:
      This code might work for you: Here is the ans of your question 
      <script type="text/javascript">
                  function validate(){
                      var phoneNo = document.getElementById('txtEmailormob');
                      var c=document.forms["myForm"]["email"].value;
                      var atpos=c.indexOf("@");
                      var dotpos=c.lastIndexOf(".");
                      var errorMsg = document.getElementById("errorMsg");
                      var successMsg = document.getElementById("successMsg");
      
                      if(phoneNo.value==""||phoneNo.value==null){
                      errorMsg.style.display="block";
                      document.getElementById("errorMsg").innerHTML = "Please enter your Mobile No or Email  ";
                          return false;
                       }
                      if ((phoneNo.value.length < 10 || phoneNo.value.length > 10) && (atpos<1 || dotpos<atpos+2 || dotpos+2>=c.length)) {
                      errorMsg.style.display = "block";
                      successMsg.style.display = "none";
                      document.getElementById("errorMsg").innerHTML = "  Mobile No. is not valid, Please Enter 10 Digit Mobile No or Please Enter valid Email. ";
                      return false;
                  }
                      successMsg.style.display = "block";
                      document.getElementById("successMsg").innerHTML = " Success ";
                      errorMsg.style.display = "none";
                      return true;
                      }
                  </script>
      

      【讨论】:

        【解决方案4】:

        您可以使用角度表单验证和 ng-pattern 指令进行输入使用ng-pattern="/^(?:\d{10}|\w+@\w+\.\w{2,3})$/"

        Working Demo

        var app = angular.module("MY_APP", []);
        app.controller("MyCtrl", function($scope) {
          $scope.submitted = false;
          $scope.submit = function(userData){
          	console.log(userData)
          }
        });
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
        <div ng-app="MY_APP">
          <div ng-controller="MyCtrl">
          <form name="userForm" novalidate ng-submit="userForm.$valid && submit(userData)">
                      <div class="errorMsg" ng-show="submitted==true && userForm.$invalid">
                            <ul>
                                <li ng-show="submitted==true && userForm.emailphone.$error" class="errorMsg">
                                    wrong format, It should be email or 10 digit mobile number
                                </li>
                            </ul>
                        </div>
            <input type="text" name="emailphone" ng-model="userData.user" id="emailphone"  required
            ng-pattern="/^(?:\d{10}|\w+@\w+\.\w{2,3})$/" />
            <button type="submit" ng-click="submitted = true">Submit</button>
        </form>
        </div>
        </div>

        【讨论】:

        • 我不认为这是错误的电子邮件sanat.gupta@gmail.com,但是从您的函数中收到了错误的电子邮件。
        【解决方案5】:

        使用/^([_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,5}))|(\d+$)$/

        Demo

        【讨论】:

        • 电话号码最小限制或最大限制不起作用
        【解决方案6】:

        您可以使用管道“|”将两个正则表达式组合在一起:

        /<email-pattern>|<phone-pattern>/
        

        所以你的最终正则表达式是:

        /^([_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,5}))|\d+$/
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-05
          • 2014-04-25
          • 2020-04-05
          相关资源
          最近更新 更多