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.

2
  • see this: stackoverflow.com/questions/16091218/… AND stackoverflow.com/questions/21432677/… Commented May 5, 2015 at 17:37
  • You can check 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. Commented Dec 25, 2015 at 19:31

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Hey, just one more question, I need that the user be able to enter ".", like 156.152. so ?
I updated the regex to allow decimals, though it will allow multiple decimals in a row
Use transformedInput = inputValue.replace(/\.\.+/g, '.'); to remove redundant periods.
thanks @Charles. I updated the JsFiddle and my answer with your suggestion.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.