简体   繁体   中英

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();
            }
          });
        }
      };
    })

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM