-2

Input field should allow only numbers from 0-9, if not number the value entered should not even display in the field. I have tried achieving this using directive which uses $parsers

 app.directive('onlyNumber', function() {
return {
  require: 'ngModel',
  restrict: 'A',
  link: function(scope, element, attrs, modelCtrl) {
    modelCtrl.$parsers.push(function(inputValue) {
      if (inputValue == null)
        return ''
      cleanInputValue = inputValue.replace(/[^\w\s]/gi, '');
      if (cleanInputValue != inputValue) {
        modelCtrl.$setViewValue(cleanInputValue);
        modelCtrl.$render();
      }
      return cleanInputValue;
    });
  }
}

});

This allows characters, and restricts only special characters, I want restric anything other than number.

Aravind
  • 40,391
  • 16
  • 91
  • 110
maaz
  • 3,534
  • 19
  • 61
  • 100
  • Possible duplicate of [HTML text input allows only numeric input](https://stackoverflow.com/questions/469357/html-text-input-allows-only-numeric-input) – Makyen Jan 29 '18 at 23:32

4 Answers4

3

you can try the below code to restrict it to only numeric characters.

    app.directive('onlyNumber', function () {
    return {
        require: 'ngModel',
        restrict: 'A',
        link: function (scope, element, attr, modelCtrl) {
            function fromUser(text) {
                if (text) {
                    var transformedInput = text.replace(/[^0-9-]/g, '');
                    if (transformedInput !== text) {
                        modelCtrl.$setViewValue(transformedInput);
                        modelCtrl.$render();
                    }
                    return transformedInput;
                }
                return undefined;
            }
            modelCtrl.$parsers.push(fromUser);
        }
    };
});

Arzoo
  • 67
  • 6
2

Regex: ^\b[0-9]+\b or ^[0-9]+$ or ^\d+$

var input1 = '8547'
var input2 = 'fasd55dasd 884'

console.log(/^\b[0-9]+\b/.test(input1), /^[0-9]+$/.test(input2));
Srdjan M.
  • 3,310
  • 3
  • 13
  • 34
1

You can replace your regex so it allows only numbers. Instead of /[^\w\s]/gi try /\D/gi

For more details you can read about regexs here

Manos Pasgiannis
  • 1,693
  • 1
  • 18
  • 30
1

You should

  1. Define DigitRegExp=/^\d+$/ in the scope
  2. add attribute ng-pattern=“DigitRegExp”
Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50