How to restrict the filling of only numbers in an input with Angularjs?

Asked

Viewed 8,717 times

5

I noticed that the page has the following code for an input:

<div class="form-group required col-md-3">
    <label for="area" class="control-label">ÁREA(ha):</label>
    <input id="area" type="text" class="form-control" data-ng-model="ctrl.area" />
</div>

Then I changed the input type, using the type"number" specified in HTML5.

<input id="area" type="number" class="form-control" data-ng-model="ctrl.area" />

In Chrome it worked, however in Firefox and Internet Explorer I was able to fill it with alpha characters. I tried to use the Pattern attribute, but I was unsuccessful.

<input id="area" type="number" pattern="[0-9]*" class="form-control" data-ng-model="ctrl.area" />

Any suggestions, directives or functions of Angularjs?
Firefox:47.0.1
Internet Explorer 11

  • 1

    Have you tried ng-Pattern?

  • @Diegoaugusto tried, continue allowing informs alpha characters.

  • Allow will continue even, but will give error in the form when trying to do Submit. If you want to block number entry, you will need a directive, e.g.: https://hassantariqblog.wordpress.com/2015/04/25/angularjs-directive-to-allow-number-only-in-textbox/

2 answers

3

//directive

app.directive('numericOnly', function(){
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, modelCtrl) {

            modelCtrl.$parsers.push(function (inputValue) {
                var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;

                if (transformedInput!=inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }

                return transformedInput;
            });
        }
    };
});

//html

<input id="area" type="text" class="form-control" data-ng-model="ctrl.area" numeric-only/>
  • 3

    Always try to add an explanation to your answer, and not just give the raw code. More important than making it work, is knowing how to make it work.

  • The directive works in essence, but allows the inclusion of multiple points and multiple negative signals.

2

Man I went through this problem and decided to dedicate myself to creating a directive that solves me the problem and as you can see below, she got big.

basically you put as attribute of your input a number-only and ready, by default it only accepts whole numbers and positive.

If you want decimal numbers you put number-only="." or number-only="," she accepts , and . as decimal separator to display in the view.

If you want negative numbers you put number-only="-" and ready, you can insert the - in front of the number.

If you want to accept any numbers number-only="-." number-only="-,", it will accept decimal and negative numbers plus positive integers.

Attention! It does not accept thousand separator, like 1.000,00, only symbol to separate decimal integers, and only the symbol you chose in the directive statement( , or . )

.directive('numberOnly', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      var negativo = /\-/.test(attrs.numberOnly);
      var decimal = /\.|\,/.test(attrs.numberOnly) ? /\.|\,/.exec(attrs.numberOnly)[0] : null;

      var regExp = '^';
      regExp += negativo ? '[\\-]{0,1}' : '';
      regExp += '[\\d]+';
      if(decimal != null) {
        regExp += '[\\'+decimal+'][\\d]+|';
        if(negativo) {
          regExp += '[\\-]{0,1}'
        }
        regExp += '[\\d]+'
      }
      regExp += '';
      regExp = new RegExp(regExp);

      ngModel.$parsers.unshift(function(input) {
        if(input === undefined) return null;
        if(input === null) return;

        input = input.toString().replace(/\./, decimal);
        if(input == '-') return input;
        if(decimal !== null && input.charAt(input.length-1) == decimal) return input;

        input = regExp.test(input) ? regExp.exec(input)[0] : null;

        var viewVal = null;

        if (input !== null) {
          input = decimal != null ? parseFloat(input.replace(/\,/, '.')) : parseInt(input);
        }

        viewVal = isNaN(input) || input === null ? '' : input;

        ngModel.$setViewValue(decimal != null ? viewVal.toString().replace(/\./, decimal) : viewVal.toString());
        ngModel.$render();

        return isNaN(input) ? null : input;
      });

      ngModel.$formatters.unshift(function(value) {
        if(value !== undefined && value !== null) {
          return decimal != null ? value.toString().replace(/\./, decimal) : value.toString();
        }
      });
    }
  }
});

HTML

<input ng-model="var1" number-only />        // apenas inteiros positivos
<input ng-model="var2" number-only="." />    // apenas decimais positivos, separados por ponto
<input ng-model="var3" number-only="," />    // apenas decimais positivos, separados por vírgula
<input ng-model="var4" number-only="-" />    // apenas números inteiros positivos ou negativos
<input ng-model="var5" number-only=",-" />   // quaisquer números inteiros ou decimais, positivos ou negativos separados por vírgula
<input ng-model="var6" number-only="-." />   // quaisquer números inteiros ou decimais, positivos ou negativos separados por ponto
  • When performing the parseFloat you perform a replace in a variable tInput, which does not exist. The code then returns error. Even when tInput for input the code continued giving problem when the field is empty and type a letter.

  • Sorry, I copied the code I made in a project and I was changing but this part I left the original, I’ll fix it. Thanks for the touch

  • @Felipelion ready, fixed and tested. Can you get the new code ai.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.