4

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 ?

1 Answer 1

5

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="... >
Sign up to request clarification or add additional context in comments.

8 Comments

wat is the ng-pattern for empty input over here ?
The addition of |^$ will add a second match possibility to the regex, where ^$ is basically saying match on the beginning of the, followed immediately by the end of line, and the | is of course just "or".
i wil try this code out and update if it works. thanks for the inputs n explaination
sorry. yes, it did work. accepted it as an answer. thanks for the answer
Can you provide some samples of valid input?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.