javascript - 正则表达式验证 AngularJs

标签 javascript angularjs regex

我在使用 ng-pattern 验证正则表达式、调用 ng-blur 和创建自定义指令时遇到问题。

我将分享所有案例场景

案例1.使用ng-pattern

Js相关代码:`$scope.regex =/^[789]\d{9}$/;

HTML

  <div class="form-group">
                <label for="mobile">Mobile Number</label>
                <div class="input-group">
                  <span class="input-group-addon">+91</span><input type="number" class="form-control" ng-model="user.mobile"  ng-pattern="regex" placeholder="Enter phone Number..."/>
                </div>

                 <span>Mobile valid = {{form.input.$valid}}</span>
              </div>

案例 2:使用 ng-blur

HTML代码

  <div class="form-group">
                <label for="mobile">Mobile Number</label>
                <div class="input-group">
                  <span class="input-group-addon">+91</span><input type="number" class="form-control" ng-model="user.mobile"  ng-pattern="regex" placeholder="Enter phone Number..." ng-blur="mobileCheck(user)"/>
                </div>
              <div ng-show="form.$submitted || form.mobile.$touched">
                  <span ng-show="showMobileError">Enter valid mobile no</span>
              </div>

              </div>

JS代码

 $scope.mobileCheck = function(user){
  var mobileRegex = /^[789]\d{9}$/;
  if(mobileRegex.test(user.mobile) && user.mobile.length ===10){
    $scope.showMobileError = false;
  }else{
    $scope.showMobileError = true;
  }

}

案例 3:对移动设备和日期使用单独的指令(我在下面包含了完整的代码)

对于日期,我也尝试执行相同的前两种情况,然后是自定义指令。嗯,该指令适用于覆盖电子邮件,但我不确定用什么值替换 number 字段和 text 字段。 即在行中替换电子邮件的内容

ctrl.$validators.**email** && ctrl.$validators.**email**

电子邮件验证指令称为 overwriteEmail,并在 app.js 文件中提到

我的app.js

var app = angular.module("formList", ['ngMessages']);
app.controller("myCtrl", ['$scope', function($scope){
$scope.formElements = [];
// $scope.jdDate = "";
var regexDate = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
// $scope.regex = regexDate;
$scope.regex = '\\d+';
$scope.dateCheck = function(user){
var regexDate = '/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/';
// alert('I am here');
     return regexDate.test(user.date);
}   


$scope.mobileCheck = function(user){
  var mobileRegex = /^[789]\d{9}$/;
  if(mobileRegex.test(user.mobile) && user.mobile.length ===10){
    $scope.showMobileError = false;
  }else{
    $scope.showMobileError = true;
  }

}

$scope.update =  function (user){

    // $scope.formElements = angular.copy(user);
     // angular.forEach(user, function(value, key){
     //      $scope.formElements.push(key + ': ' + value);
     // }) 
     $scope.formElements.push(
     {

      mobile: user.mobile, 
      name: user.firstName + user.lastName, 
      email: user.email,
      altMobile: user.altMobile,
      dob: user.dob, 
      gender: user.gender, 
      pincode: user.pincode, 
      address: user.address, 
      district: user.district, 
      state: user. state

    }
  );

    $scope.showResults = true;

}

$scope.reset = function() {
    $scope.user = angular.copy($scope.formElements);
};

$scope.delete = function(user, index) {
  $scope.formElements.splice(index, 1);
}

}]);

app.directive('overwriteEmail', function() {
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@justdial\.com$/i;

return {
require: 'ngModel',
restrict: '',
link: function(scope, elm, attrs, ctrl) {
  // only apply the validator if ngModel is present and Angular has added  the email validator
  if (ctrl && ctrl.$validators.email) {

    // this will overwrite the default Angular email validator
    ctrl.$validators.email = function(modelValue) {
      return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
     };
    }
  }
};
});
  // app.directive('jdDate',function () {
  //    return {
  //        replace:true,
  //        scope:{
  //            jdModel:"="
  //        },
 //         template:"<input type='text' ng-model='abc' />",
 //         link:function (scope) {

//          scope.jdModel = "123";
//      }
//  }
// })
app.directive('dateValidator', function() {
 var dateregex = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;

return {
 require: 'ngModel',
 restrict: '',
 link: function(scope, elm, attrs, ctrl) {
  // only apply the validator if ngModel is present and Angular has added the email validator
  if (ctrl && ctrl.$validators.uDate) {


    ctrl.$validators.uDate = function(modelValue) {
      return ctrl.$isEmpty(modelValue) || dateregex.test(modelValue);
    };
  }
}
};
});

<html ng-app="formList">
<head>
  <meta charset="UTF-8">
  <title>Day 7 Angular Workaround</title>
  <link href="css/styles.css" media="screen, projection" rel="stylesheet" type="text/css" />

  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

  <!-- Optional theme -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

  <script src="js/angular.js" type="text/javascript"></script>
   <script src="https://code.angularjs.org/1.4.9/angular-messages.js"></script>


 
</head>
<body ng-controller="myCtrl">
  <div class="container">


    <button class="btn btn-info" data-toggle="modal" data-target="#customerModal"><span class="glyphicon glyphicon-user"></span>Add Customer</button>

    <div class="modal fade" id="customerModal" tabindex="-1" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">Add/Search Customer</h4>
          </div>
          <div class="modal-body">
            <form id="form" name="form" novalidate>

              <div class="col-sm-6">
                  <h3>Customer Details</h3>
                  <div class="form-group">
                    <label for="mobile">Mobile Number</label>
                    <div class="input-group">
                      <span class="input-group-addon">+91</span><input type="number" class="form-control" ng-model="user.mobile"  ng-pattern="regex" placeholder="Enter phone Number..." ng-blur="mobileCheck(user)"/>
                    </div>
                  <div ng-show="form.$submitted || form.mobile.$touched">
                      <span ng-show="showMobileError">Enter valid mobile no</span>
                  </div>
                     <!-- <span>Mobile valid = {{form.input.$valid}}</span> -->
                  </div>

                  <div class="form-group">
                    <label>Name(Optional)</label>
                    <ul class="list-inline">
                      <li><input type="text" class="form-control" ng-model="user.firstName" placeholder="First name" /></li>
                      <li><input type="text" class="form-control" ng-model="user.lastName" placeholder="Last name" /></li>
                    </ul>
                     
                  </div>

                  <div class="form-group">

                    <label for="email">Email(optional)</label>
                    <input type="email" class="form-control" ng-model="user.email" placeholder="Enter Email id here" />
                     
                  </div>
                  <div class="form-group">
    
                    <label for="altMobile">Alternate contact No.(optional)</label>
                    <div class="input-group">
                      <span class="input-group-addon">+91</span> <input type="number" class="form-control" ng-model="user.altMobile" placeholder="Enter Alternate Mobile here" />
                    </div>
                   
                     
                  </div>

                  <div class="form-group">

                    <label for="dob">Date Of birth(optional)</label>
                    <input type="text" class="form-control" ng-model="user.dob" />
                     
                  </div>


                  <div class="form-group" id="gender">

                    <label>Gender(optional)</label>
                   
                    <div class="input-group">
                      <label for="male"><input type="radio" ng-model="user.gender" name="gender" value="male" />Male</label> 
                      <label for="female"><input type="radio" ng-model="user.gender" name="gender" value="female" />Female</label>
                      <label for="others"><input type="radio" ng-model="user.gender" name="gender" value="others" />Others</label>                      
                    </div>
 
                     
                  </div>
                 


              </div>
              <div class="col-sm-6">
                <h3>Residential Address</h3>

                <div class="form-group">

                    <label>Pincode(optional)</label>
                    <input type="number" class="form-control" name="pincode" ng-model="user.pincode" placeholder="Enter Pincode" />
                     
                </div>


               
                <div class="form-group">
                    <label for="address">Address(optional)</label>
                    <textarea ng-model="user.address" class="form-control" name="address" id="address" cols="30" rows="6" placeholder="Enter address details"></textarea>
                </div>

                <div class="form-group">
                    <label for="district">District(optional)</label>
                    <input type="text" ng-model="user.district" class="form-control" name="district" placeholder="Enter District here">
                </div>
                <div class="form-group">
                    <label for="district">State(optional)</label>
                    <input type="text" ng-model="user.state" class="form-control" name="state" placeholder="Enter State here">
                </div>
                <div class="form-group">
                    <label for="district">Country</label>
                    <input type="text" ng-model="user.country" class="form-control" value="india" name="country" placeholder="India(This service is only within India" disabled>
                </div>


              </div>
               
             <!--  <div class="clearfix"></div>
              <div class="col-sm-offset-3 col-sm-9">
                  <button type="button" class="btn btn-default" id="reset" ng-click="reset()">Reset</button>
                  <button type="submit" class="btn btn-default" id="submit" ng-click="update(user)">Save &amp; Show</button>
              </div> -->
            </form> 
          <div class="clearfix"></div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            <button type="button" class="btn btn-primary" ng-click="update(user)"><span class="glyphicon glyphicon-user"></span> Add Customer</button>
          </div>
        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
   
    <div id="showResults" ng-show="showResults" >
      <table class="table table-responsive table-bordered table-striped">
        <thead>
          <tr>
            <th>Name</th>
            <th>Mobile</th>
            <th>Email</th>
            <th>Alternate Number</th>
            <th>Date of Birth</th>
            <th>Gender</th>
            <th>Pincode</th>
            <th>Address</th>
            <th>District</th>
            <th>State</th>
            <th>Action</th>
          </tr>
        </thead>
        
      
        <tbody>
          <tr ng-repeat="item in formElements" class="active">

           <!--  <td ng-click="editing=true"><span>{{item.name}}</span> <span class="glyphicon glyphicon-edit" ng-hide="editing"></span><input type="text" ng-model="item.name" ng-show="editing" ng-blur="editing=false" /></td> -->

             <td ng-click="editing=true" ng-repeat="td in item"><span>{{td}}</span> <span class="glyphicon glyphicon-edit" ng-hide="editing"></span><input type="text" ng-model="td" ng-show="editing" ng-blur="editing=false" /></td>

           
            <td><span class="glyphicon glyphicon-remove-circle action-btns" ng-click="delete(user, $index)"></span></td> 
          </tr>
        </tbody>
      
      
      </table>
    </div>
      
    </div>
  </div>
  <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
    <!-- Latest compiled and minified JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
  <script type="text/javascript" src="js/final.js"></script>

</body>
</html>

我很想知道这三种情况的解决方案。

最佳答案

问题在于使用了输入类型=“数字”。使用 type="text"即可验证。

关于javascript - 正则表达式验证 AngularJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35200508/

相关文章:

javascript - 如何根据输入到 ng-model 中的数量添加新 html 元素的数量

java - 什么是 Java 正则表达式来匹配数字然后空格然后 3 个字母字符?

python - 将声明性测试转换为 pytest 断言

regex - 在将其用于替换之前对正则表达式中捕获的数字进行计算

javascript - 加载动态 HTML - 服务器端或客户端

angularjs - 在同一项目中同时使用 Backbone.js 和 Angular.js。其可行性和实际意义是什么?

url-routing - 在Angular.js中的子目录中路由

javascript - 构建 JavaScript : Writing a basic validator

javascript - 等待 DOM 在 AngularJS 指令上准备就绪

javascript - ASP.NET 检测 Javascript 是否禁用字段