0

I am trying to pass two regex variable regex1 and regex2 for email and mobile number into single ng-pattern by using "OR" condition but it is not working. if i pass a single variable at a time then it works perfectly. So what i have to do to pass two variable at a time into single ng-pattern directive. please suggest solution..

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="utf-8">
    <title>Form Validate</title>
    <style>
        input.ng-invalid.ng-dirty{border:1px solid red;}
    </style>
</head>
<body>
 <div ng-controller="myCtrl">
  <form name="frm">
    <input type="text" name="udetail" ng-model="user.udetail" placeholder="Enter email or phone number" ng-pattern="regex1 || regex2" required>
     <span ng-show="frm.udetail.$dirty && frm.udetail.$error.required">required</span><br>

  </form>
 </div>
  <script src="https://code.angularjs.org/1.2.3/angular.min.js"></script>
  <script>
    var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
    $scope.regex1 = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    $scope.regex2 = /^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$/;
});
  </script>
</body>
</html>
Sunny
  • 577
  • 6
  • 20

1 Answers1

1

What you can do is create a function in which you can taken both regex and based on these regex return true and false and from ng-pattern call that function

    <!DOCTYPE html> <html lang="en" ng-app="myApp"> <head>
        <meta charset="utf-8">
        <title>Form Validate</title>
        <style>
            input.ng-invalid.ng-dirty{border:1px solid red;}
        </style> </head> <body>  <div ng-controller="myCtrl">   <form name="frm">
        <input type="text" name="udetail" ng-model="user.udetail" placeholder="Enter email or phone number" ng-pattern="regex1 || regex2" required>
         <span ng-show="frm.udetail.$dirty && frm.udetail.$error.required">required</span><br>

      </form>  </div>   <script src="https://code.angularjs.org/1.2.3/angular.min.js"></script>   <script>
        var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) {
        $scope.regex1 = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        $scope.regex2 = /^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$/; }); 
        $scope.runBothRegex = (function(){

        return {
        var value = $scope.user.udetail;
        if(regex1.test(value) || regex2.test(value)){
          return true;
          }
         return false;
        }
  })();
  </script> </body> </html>
Innovation
  • 1,514
  • 17
  • 32