OptimusPrime
OptimusPrime

Reputation: 99

Limit input field after 2 decimals in angular

I have a number of input boxes on a html page. I want to restrict the user from entering any numbers after 2 decimals.

Upvotes: 1

Views: 24696

Answers (2)

404
404

Reputation: 1155

You can use this directive to achieve the same.

    .directive('validNumber', function () {
    return {
        require: '?ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            if (!ngModelCtrl) {
                return;
            }

            ngModelCtrl.$parsers.push(function (val) {
                var clean = val.replace(/[^0-9\.]+/g, '');
                if (val !== clean || val.indexOf('.') != val.lastIndexOf('.')) {
                    if (val.indexOf('.') != val.lastIndexOf('.')) {
                        clean = clean.substring(0, clean.length - 1)
                    }
                }

                if (clean.indexOf('.') != -1) {
                    if (clean.length > (clean.indexOf('.') + 3)) {
                        clean = clean.substring(0, clean.length - 1)
                    }
                }


                ngModelCtrl.$setViewValue(clean);
                ngModelCtrl.$render();
                return clean;


            });

            element.bind('keypress', function (event) {
                if (event.keyCode === 32) {
                    event.preventDefault();
                }
            });
        }
    };
})

this directive validates number inputs, and restricts to two decimal points in the input field.

Upvotes: -1

Tomislav
Tomislav

Reputation: 3211

Guilherme Ferreira described it on his blog:

Angularjs input number with two decimal places

Create the number input with the number type and step inerval

<input type="number" name="myDecimal" placeholder="Decimal" ng-model="myDecimal" *step="0.01" />

Set the regular expression to validate the input using ng-pattern. Here I want to accept only numbers with a maximum of 2 decimal places and with a dot separator

<input type="number" name="myDecimal" placeholder="Decimal" ng-model="myDecimal" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" step="0.01" />

EDIT:

This SO approaches to problem using directive: Restrict number of decimals in html5 type="number" input field (with Angularjs model)

angular.directive('decimalPlaces',function(){
    return {
        link:function(scope,ele,attrs){
            ele.bind('keypress',function(e){
                var newVal=$(this).val()+(e.charCode!==0?String.fromCharCode(e.charCode):'');
                if($(this).val().search(/(.*)\.[0-9][0-9]/)===0 && newVal.length>$(this).val().length){
                    e.preventDefault();
                }
            });
        }
    };
});

Then use it in your HTML:

<input  type="number" step="0.01" ng-model='somemodel' decimal-places>

Upvotes: 4

Related Questions