saurav
saurav

Reputation: 219

multiple Text box input validation check

I am writing one textbox validation that actually disallows user to enter some invalid special character. Once user enters a invalid special character I am throwing a hard error prompt and I am setting a flag:

$scope.charAllowedText = false;

So the next button will get disabled if the input box has any invalid value. As soon as user deletes the invalid character I am just changing this flag to true. My solution works fine for single text box but this is not working for multiple text input.

On each user onClick am calling this validation:

$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'
    });
  }
};

For a particular case if I remove the invalid character in one of text boxes and other text boxes still have invalid characters my next button gets enabled since the flag value was set to true by the first text box.

Upvotes: 0

Views: 187

Answers (1)

geo
geo

Reputation: 2433

The right way to write a validation check should be to create a directive. The reason for this is that you want to keep your validator as stateless as possible. The problem to your workaround is that you use the same variable in order to check if the the input is valid. If you want to keep your code the same is to change the function and return a true or false instead of setting the value to the variable $scope.charAllowedText

You can do that by using Angular-validator .

Also have a look at this post .

Upvotes: 1

Related Questions