Monday, February 16, 2015

Angular JS Function for Decimals , Integers validation in textbox

Angular JS Function for Decimals , Integers validation in textbox


To allow only decimals or integers in the textboxes I have very better function written below in only once place in app.js , and can be used thought the application by just including the names.

Include below functions in your app.js
//included by Ilyas to allow integers, decimals in textbox  and restricts other values
//'YourAppName' è Write your application name

angular.module("YourAppName").
    directive("onlyFloats", function () {
        return {
            require: 'ngModel',
            restrict: 'A',
            link: function (scope, element, attr, ctrl) {
                function inputValue(val) {
                    if (val) {
                        var digits = val.replace(/[^0-9.]/g, '');
                       
                        if (digits !== val) {
                            ctrl.$setViewValue(digits);
                            ctrl.$render();
                        }
                   
                        return parseFloat(digits);
                    }
                    return undefined;
                }
                ctrl.$parsers.push(inputValue);
            }
        };
});

//included by Ilyas to allow  only integers in textbox  and restricts other values
//'YourAppName' è Write your application name

angular.module('YourAppName').
  directive('onlyDigits', function () {

      return {
          restrict: 'A',
          require: '?ngModel',
          link: function (scope, element, attrs, ngModel) {
              if (!ngModel) return;
              ngModel.$parsers.unshift(function (inputValue) {
                  var digits = inputValue.split('').filter(function (s) { return      (!isNaN(s) && s != ' '); }).join('');
                  ngModel.$viewValue = digits;
                  ngModel.$render();
                  return digits;
              });
          }
      };

  });


Usage:

In your .html or .chtml page include as below :) :) >>

For only digits just include only-digits as below
<input  type="text" ng-model="XXXX" maxlength="100" only-digits >

Note: this textbox don't allow you to enter other than digits

For only decimals just include only-floats as below
<input  type="text" ng-model="XXXX" maxlength="100" only-floats >

Notethis textbox don't allow you to enter other than digits and decimals


Hope you enjoyed.......

No comments: