javascript - 使用 ng-pattern Angularjs 进行动态验证

标签 javascript html angularjs validation

我正在尝试根据从下拉列表中选择的值对输入进行验证。

JSFiddle: https://jsfiddle.net/Raj_13290/qqLnqw3f/9/

我正在更改下拉列表的 ng-change 中 ng-pattern 的值。验证工作正常,但当我更改下拉值时,之前在输入中输入的值未验证。

例如,如果我在下拉列表中选择货币并输入文本“abc”,那么它会验证,但是当我将下拉列表更改为文本时,它仍然显示无效值。

我尝试过使用更高版本的 Angular,它工作正常,但对于 1.2.23,它不起作用。

任何解决方案都值得赞赏。谢谢

最佳答案

看来这是一个错误 Angular 。

我找到了解决方案,但不是很好。

jsfiddle 上的实例.

var myApp = angular.module('myApp', []);

myApp.controller("MyCtrl", function($scope) {
  var tThis = this;
  $scope.dataTypeList = [{
    'id': 1,
    "label": "Currency"
  }, {
    'id': 2,
    "label": "Number"
  }, {
    'id': 3,
    "label": "Text"
  }];
  $scope.dataTypeValue;
  $scope.textValue = {
    text: ""
  };
  $scope.customPattern = /.*/;
  $scope.getCustomPattern = function(pInput) {
    if (!$scope.dataTypeValue)
      return $scope.customPattern;
    var dataTypeId = $scope.dataTypeValue.id;
    if (dataTypeId === 1) {
      $scope.customPattern = /^\d{1,10}$/;
    } else if (dataTypeId === 2) {
      $scope.customPattern = /^\d+$/;
    } else if (dataTypeId === 3) {
      $scope.customPattern = /^.*$/;
    }
    if (!$scope.getCustomPattern.isParser) {
      $scope.getCustomPattern.isParser = true;
      pInput.$setViewValue(pInput.$viewValue);
    } else {
      $scope.getCustomPattern.isParser = false;
    }
    return $scope.customPattern;
  };
});
input.ng-invalid {
  border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    <ng-form name="MyForm">

      <h3>
     With dynamic pattern
    </h3>
      <select ng-model="dataTypeValue" ng-options="t as t.label for t in dataTypeList" ng-change="getCustomPattern(MyForm.input)">

      </select>

      <input type="text" ng-model="textValue.text" ng-pattern="getCustomPattern(MyForm.input)" ng-model-options="{allowInvalid:true}" name="input">
      <br>
      <br>
      <br>Data type: {{dataTypeValue}}
      <br>Entered value: {{textValue}}

    </ng-form>
  </div>
</div>

关于javascript - 使用 ng-pattern Angularjs 进行动态验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36196903/

相关文章:

html - 图像 CSS 悬停时的缩放效果

javascript - 根据 AngularJS 中的条件制作所需的输入类型文件

javascript - 如何使用 jquery 添加具有不同值的不同元素

javascript - Angular 依赖注入(inject) - 无法实例化工厂/未定义的工厂

javascript - 获取表行作为链接

javascript - 数字输入中的 ng-model 不影响范围

javascript - 强制 $scope.$watch 仅触发一次

javascript - 用 jQuery 替换同一个类的链接

javascript - javascript/appcelerator 中的换行

javascript - 在整个文档上监听事件的成本是多少?