1

I am trying to set up an input which can accept only numbers, but still can put letter in it, why ?

               <input type="number"
                      pattern="[0-9]"
                      ng-model="slip.risk"
                      class="form-control"
                      placeholder="Risk"
                      ng-change="riskWinCalculations(slip, 'RISK')">

this is for an Angularjs app, so I don't know if this is the issue or what.

Non
  • 8,409
  • 20
  • 71
  • 123
  • see this: http://stackoverflow.com/questions/16091218/angularjs-allows-only-numbers-to-be-typed-into-a-text-box AND http://stackoverflow.com/questions/21432677/restrict-input-as-numbers-on-input-fields-using-angularjs?lq=1 – The Guest May 05 '15 at 17:37
  • You can check https://github.com/rajesh38/ng-only-number 1. It restricts input to only numbers and decimal point in a textbox while typing. 2. You can limit the number of digits to be allowed before and after the decimal point 3. It also trims the digits after the decimal point if the decimal point is removed from the textbox e.g. if you have put 123.45 and then remove the decimal point it will also remove the trailing digits after the decimal point and make it 123. – Rajesh Paul Dec 25 '15 at 19:31

1 Answers1

2

pattern will not prevent characters from being typed into the input element, it will only set off validation.

To prevent non numeric characters from being entered you can use a directive that intercepts the value being typed.

angular.module('components', []).directive('numbersOnly', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            ngModelCtrl.$parsers.push(function (inputValue) {
                var transformedInput = inputValue.replace(/\.\.+/g, '.');
                ngModelCtrl.$setViewValue(transformedInput);
                ngModelCtrl.$render();

                return inputValue;
            });
        }
    }
});

Here's a JsFiddle of the working directive

officert
  • 1,232
  • 9
  • 12