Search code examples
javascriptangularjsvalidationkeypress

Allow null values- input type number (angularjs)


I have the following code.

<input ng-keypress="onlyNumbers($event)" min="0" type="number" step="1" ng-pattern="/^[0-9]{1,8}$/" ng-model="... >

Now it accepts only numerical values. I want null values to be accepted too. Since there are null values in database, i want it to reflect in the UI. currently i get [Object][Object] at the input for null value.

$scope.onlyNumbers = function(event){   
  var keys = {
    'up': 38,
    // Other key codes
    ...
    '9':57
  };

  for(var index in keys) {
    if (!keys.hasOwnProperty(index)) continue;
    if (event.charCode==keys[index]||event.keyCode==keys[index]) {
      return; //default event
    }
  }

  event.preventDefault();
};

Can anyone let me know how to make it work ?


Solution

  • What if you remove the min attribute and modified the ng-pattern to check for an empty input?

    <input ng-keypress="onlyNumbers($event)" type="number" step="1" ng-pattern="/^[0-9]{1,8}$|^$/" ng-model="... >