簡體   English   中英

多個文本框輸入驗證檢查

[英]multiple Text box input validation check

我正在編寫一個文本框驗證,實際上不允許用戶輸入一些無效的特殊字符。 用戶輸入無效的特殊字符后,我會拋出一個錯誤提示並設置一個標志:

$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,因此將啟用下一個按鈕。

編寫驗證檢查的正確方法應該是創建指令。 這樣做的原因是您要使驗證器盡可能保持無狀態 解決方法的問題是,您使用相同的變量來檢查輸入是否有效。 如果要保持代碼不變,那就是更改函數並返回true或false,而不是將值設置為變量$scope.charAllowedText

您可以使用Angular-validator做到這一點。

也可以看看這個帖子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM