-3

I am having an issue while I am validating a textbox with number upto 11 digits including decimal and two digits after decimal(if any). On keyup in jquery.

I used this regular expression /^(\d+)?([.]?\d{0,2})?$/g to validate for a number and decimal with two digits, but I do not know how to constraint digits max to 11.

I have used the input type number with maxlength but it's not working.

Fiddle Is here

Html

<input type="number" />

jQuery

 $('input').keyup(function() {
        var $th = $(this);
        $th.val( $th.val().match(/^(\d+)?([.]?\d{0,2})?$/g, 
        function(str) { 
          return ''; }
          ) );
    });

Values like this

64123841.33 123456789.1 , 12345678901, 1.22,

Please Help me out with this.

wikijames
  • 192
  • 3
  • 17

2 Answers2

4
^\d{0,8}\.\d{1,2}$|^\d{0,11}$

here is the working example

Sahib Yar
  • 1,030
  • 11
  • 29
1

use a lookahead to test the length:

/^(?=.{1,11}$)\d+(?:\.\d{1,2})?$/

(?=.{1,11}$) is a lookahead that make sure we have 1 up to 11 character

(?:\.\d{1,2})? is an optional non capture group that allows 1 or 2 decimal

Toto
  • 89,455
  • 62
  • 89
  • 125