【问题标题】:multiple Text box input validation check多个文本框输入验证检查
【发布时间】:2017-03-17 13:30:55
【问题描述】:

我正在编写一个文本框验证,实际上不允许用户输入一些无效的特殊字符。一旦用户输入了一个无效的特殊字符,我就会抛出一个硬错误提示并设置一个标志:

$scope.charAllowedText = false;

所以如果输入框有任何无效值,下一个按钮将被禁用。一旦用户删除了无效字符,我只是将此标志更改为 true。 我的解决方案适用于单个文本框,但这不适用于多个文本输入。

在每个用户 onClick 上调用此验证:

$scope.validateUserInput = function(inputKey) {
  var count = 0;
  // inputKey = inputKey.replace(/[^a-zA-Z0-9 ]/g, "");
  $scope.imp = [];
  $scope.imp = Array.from(inputKey.replace(/[a-zA-Z0-9\s]/g, ''));
  var charInp = [];

  $scope.missingItems = [];
  $scope.imp.forEach(function(itemFromTarget) {
    var itemFound = false;
    for (var i in $rootScope.specialChar) {
      if (itemFromTarget === $rootScope.specialChar[i].value) {
        itemFound = true;
      }
    }

    if (!itemFound) {
      $scope.charAllowedText = false;
      $scope.missingItems.push(itemFromTarget);
    }
  });

  if (($scope.charAllowedText == false)) {
    $rootScope.charAllowedConfig = $scope.charAllowedText;
    $scope.header_class = 'modal-error-header';
    $scope.cancel_bttn = {
      txt: 'Ok',
      class: 'btn-default'
    };
    $scope.action_bttn = {};
    $modal({
      scope: $scope,
      templateUrl: 'flexi-modal.html',
      title: 'Error!',
      content: '<p class="alert alert-danger">You have entered the ' + $scope.missingItems[0] + ' character which is not supported. Please reenter a different character.</p>',
      html: true,
      show: true,
      animation: 'am-fade-and-scale',
      placement: 'center'
    });
  }
};

对于特定情况,如果我删除了其中一个文本框中的无效字符,而其他文本框中仍有无效字符,我的下一个按钮将启用,因为第一个文本框将标志值设置为 true。

【问题讨论】:

  • 添加一个 plunker 以了解您的意思或告诉我们什么是通过和什么不通过

标签: javascript angularjs


【解决方案1】:

编写验证检查的正确方法应该是创建一个指令。这样做的原因是您希望您的验证器尽可能无状态。您的解决方法的问题是您使用相同的变量来检查输入是否有效。如果要保持代码不变,请更改函数并返回 true 或 false,而不是将值设置为变量 $scope.charAllowedText

您可以使用 Angular-validator 来做到这一点。

也看看这个post。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 2011-04-12
    • 1970-01-01
    相关资源
    最近更新 更多