代码之家  ›  专栏  ›  技术社区  ›  kaka1234

AngularJs文本框验证,限制使用正则表达式负前瞻的字符

  •  0
  • kaka1234  · 技术社区  · 6 年前

    在这里使用angular js:

    我有一个文本框,我想在其中应用某些正则表达式并阻止用户使用某些字符。以下是我想要的:

    • 防止用户以下划线开始和结束。
    • 允许使用字符和数字,并且可以以任意一个开头或结尾
    • 字符/数字之间只允许使用下划线,并且在 开始或结束。

    文本框:

     <input type="text" name="uname" ng-model="uname" required class="form-
      control input-medium" placeholder="Enter  name..." maxlength="20" restrict-
      field="alpha-numeric" ng-trim="false" />
    

    .directive("restrictField", function() {
    return {
      require: "ngModel",
      restrict: "A",
      link: function(scope, element, attrs, ctrl) {
        var regReplace,
          preset = {
            "alphanumeric-spl": "\\w_./s/g",
            "alphanumeric-underscore": "\\w_",
            "numeric": "0-9",
            "alpha-numeric": "\\w"           
          },
          filter = preset[attrs.restrictField] || attrs.restrictField;
    
        ctrl.$parsers.push(function(inputValue) {
          regReplace = new RegExp('[^' + filter + ']', 'ig');
    
          if (inputValue == undefined) return "";
          cleanInputValue = inputValue.replace(regReplace, "");
          if (cleanInputValue != inputValue) {
            ctrl.$setViewValue(cleanInputValue);
            ctrl.$render();
          }
          return cleanInputValue;
        });
      }
       };
      });
    

    虽然上述方法适用于我在指令中使用的简单模式,但不适用于我上面描述的模式。从我的另一篇文章中,我得到了用于正则表达式负前瞻的模式,如下所示:

    ^(?!_)(?!.*_$)[a-zA-Z0-9_]+$
    

    但是,如果我试图将其包含在指令中,这是行不通的。

    以下是我创建的示例代码笔: https://codepen.io/anon/pen/LJBbQd

    1 回复  |  直到 6 年前
        1
  •  0
  •   Wiktor Stribiżew    6 年前

    我建议允许 _ 具有 pattern=".*[^_]" . 如果需要允许空字符串,请使用 pattern="(?:.*[^_])?"

    var app = angular
      .module("myApp", ["ui.bootstrap"])
      .directive("restrictField", function() {
        return {
          require: "ngModel",
          restrict: "A",
          link: function(scope, element, attrs, ctrl) {
            var regReplace,
              preset = {
                'alphanumeric-spl': '[^\\w\\s./]+', // Removes all but alnum, _ . / whitespaces
                'alphanumeric-underscore': '^_+|_+(?=_)|\\W+', // Removes all _ at start and all _ before a _ and all but alnum and _
                'numeric': '[^0-9]+', // Removes all but digits
                'alpha-numeric': '[\\W_]+' // Removes all but alnum
              },
              filter = preset[attrs.restrictField] || attrs.restrictField;
    
            ctrl.$parsers.push(function(inputValue) {
              console.log(filter);
              regReplace = RegExp(filter, 'ig');
    
              if (inputValue == undefined) return "";
              cleanInputValue = inputValue.replace(regReplace, "");
              if (cleanInputValue != inputValue) {
                ctrl.$setViewValue(cleanInputValue);
                ctrl.$render();
              }
              return cleanInputValue;
            });
          }
        };
      });
    
    // Define the `appController` controller on the `ReportsMockUpsApp` module
    app.controller("ctrl", function($scope) {});
    body {
      padding: 10px
    }
    
    input:valid {
      color: black;
      border: 5px solid #dadadada;
      border-radius: 7px;
    }
    
    input:invalid {
      color: navy;
      outline: .glowing-border:focus;
      border-color: #ff1050;
      box-shadow: 0 0 10px #ff0000;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.4/ui-bootstrap-tpls.min.js"></script>
    <script src="https://code.angularjs.org/1.3.4/angular.min.js"></script>
    <div class="container" ng-app="myApp">
      <div ng-controller="ctrl">
        <label>Wow</label>
        <input type="text" pattern=".*[^_]" name="uname" ng-model="uname" required class="form-control input-medium" placeholder="Enter  name..." maxlength="20" restrict-field="alphanumeric-underscore" ng-trim="false" />
    
    
      </div>
    </div>