user2138675
user2138675

Reputation: 95

Javascript regExp to accept 12 digits before decimal and two digits after decimal

Can anyone tell me the javascript regEx to accept 12 numbers before decimal and to allow only 2 digits after decimal.In case the number does not have any decimal, the text box should accept max of 12 numbers.The value should be only numbers. I already have a directive where i am performing all the javascript validations.Please let me know what else should be added.

The directive-

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

          ngModelCtrl.$parsers.push(function(val) {
            if (angular.isUndefined(val)) {
                var val = '';
            }


            var decimalCheck = clean.split('.');

            if(!angular.isUndefined(decimalCheck[1])) {
                decimalCheck[1] = decimalCheck[1].slice(0,2);
                clean = decimalCheck[0] + '.' + decimalCheck[1];
            }

            if (val !== clean) {
              ngModelCtrl.$setViewValue(clean);
              ngModelCtrl.$render();
            }
            return clean;
          });

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

Upvotes: 0

Views: 1403

Answers (1)

CoderPi
CoderPi

Reputation: 13221

This is the RegEx you are looking for: /^\d{1,12}(\.\d{1,2})?$/

Demo (try it yourself):

var input = document.getElementsByTagName("input")[0]
input.oninput = function() {
  document.getElementById("output").textContent = /^\d{1,12}(\.\d{1,2})?$/.test(input.value)
}
<input type="text" />
<div id="output"></div>

Upvotes: 4

Related Questions