Michel Ayres
Michel Ayres

Reputation: 5985

How can I make this "percentage-only" Regex works?

I'm trying to achieve a scenario where I can limit my string to tree digits one dot and two digits being the dot and the last two digits optional.

e.g.:

I could achieve a regex that allow me to avoid other besides dot and comma, and I remove the extra dots.

function isPercentage(input){
    var regex = /[^0-9\.]/g;

    var value = input.replace(regex, '');
    var index = value.indexOf( '.' );
    if ( index > -1 ) {
        value = value.substr( 0, index + 1 ) +
        value.slice( index ).replace( /\./g, '' );
    }
    return value;
}

I tried the following regex, based on knowledge of regex (if it can be considered any...)

var regex = /^[0-9]{3}\.{1}[0-9]{2}$/g;

But now it doesn't show any error nor it work at all.


I'm using this function in jQuery(document).on('focusout',, jQuery(document).on('paste', and jQuery(document).on('keyup', (I separated them to make things easy to ready)

Snippet

jQuery(document).ready(function(){
  jQuery(document).on('focusout','.decimal_only', function(){
    jQuery(this).val(isPercentage(jQuery(this).val()));
  });
  
  jQuery(document).on('paste','.decimal_only', function(){
    var element = jQuery(this);
    setTimeout(function () {
      var v = element.val();
      element.val(isPercentage(v));
    }, 100);
  });
  
  jQuery(document).on('keyup','.decimal_only', function(){
    var kc = event.keyCode;
		var cmdKeys = [9,13,16,17,18,19,20,27,33,34,35,36,37,38,39,40,45,91,92,93,96,97,98,99,100,101,102,103,104,105,112,113,114,115,116,117,118,119,120,121,122,123,144,145];
		if(jQuery.inArray(kc,cmdKeys) == -1) {
			jQuery(this).val(isPercentage(jQuery(this).val()));
		}
	});
});

function isPercentage(input){
  var regex = /[^0-9\.]/g;

  var value = input.replace(regex, '');
  var index = value.indexOf( '.' );
  if ( index > -1 ) {
    value = value.substr( 0, index + 1 ) +
      value.slice( index ).replace( /\./g, '' );
  }
  return value;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="decimal_only" />

Upvotes: 4

Views: 104

Answers (1)

JuniorCompressor
JuniorCompressor

Reputation: 20025

Try:

/^\d{1,3}(\.\d{1,2})?$/m;

With \d{1, 3} you ask for 1 to 3 digits. With \.\d{1,2} you ask for a dot followed by 1 to 2 digits. Putting the previous expression inside (...)? you make it optional.

Upvotes: 3

Related Questions