1

I'm trying to validate one input field in such way, that it wont accept anything except numbers ant '+' sign. While searching for solution I found this answer. angularjs validate input and prevent change if invalid It worked for me, but I cant delete anything from inputfield in my browser, after I've written something.

var app = angular.module('ContactUsScreen', ['ngMessages']);
app.controller('ContactUsScreenController', function($scope, $http) {

  $scope.validValues = ['+', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
});

app.directive('myValidator', function($parse) {
  return {
    scope: {
      validValues: '=validValues'
    },
    link: function(scope, elm, attrs) {
      elm.bind('keypress', function(e) {
        var char = String.fromCharCode(e.which || e.charCode || e.keyCode),
          matches = [];
        angular.forEach(scope.validValues, function(value, key) {
          if (char === value) matches.push(char);
        }, matches);
        if (matches.length == 0) {
          e.preventDefault();
          return false;
        }
      });
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="ContactUsScreen" lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link href="css/bootstrap.css" rel="stylesheet">
  <style>
    body {
      padding-top: 60px;
    }
    textarea {
      resize: none;
    }
  </style>
  <script src="js/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-messages.js"></script>
  <script src="js/contact.js"></script>
</head>

<body ng-app="app" ng-controller="ContactUsScreenController">

  <div id="formDiv" class="container">
    <form ng-submit="submitForm()" id="contactForm" name="contactForm" class="form-horizontal" novalidate>

      <div class="form-group" id="inputPhoneDiv" ng-class="{ 'has-error': contactForm.phoneNr.$invalid && !contactForm.phoneNr.$pristine}">
        <label for="inputPhone" class="col-xs-2">Phone number</label>
        <div class="col-xs-10">
          <input type="text" my-validator valid-values="validValues" name="phoneNr" class="form-control" id="inputPhone">
        </div>
      </div>
    </form>
  </div>

I understand that in someway e.preventDefault() blocks keypress method of my backspace button. I cant quite figure out how to deal with this, how to add kind of exception for backspace and delete buttons, so e.preventDeafult() would not block them. Can I have some help on how to do that?

Community
  • 1
  • 1
Martin
  • 177
  • 1
  • 11

1 Answers1

2

Why not simply doing something like this?

link: function(scope, elm, attrs) {
      elm.bind('keypress', function(e) {
      var key = e.keyCode || e.charCode;

if( key == 8 || key == 46 )
    return true;

        var char = String.fromCharCode(e.which || e.charCode || e.keyCode),
          matches = [];
        angular.forEach(scope.validValues, function(value, key) {
          if (char === value) matches.push(char);
        }, matches);
        if (matches.length == 0) {
          e.preventDefault();
          return false;
        }
      });

You don't need to run the whole logic if it's a key you trust (like backspace)

Christian
  • 6,961
  • 10
  • 54
  • 82