How to limit the number of houses before the comma in a regular expression?

2

I'm using this expression to not let the user type a dot before any number and limiting 2 boxes after the comma, but I also needed to limit 5 boxes before the comma, the way I am I can insert as many numbers as I can before the comma . Does anyone know how I can do this? I'm catching up here.

My expression: "([0-9]+(\.)?([0-9]?[0-9]?))"

    
asked by anonymous 04.12.2015 / 18:02

2 answers

2

The same way you did to limit it later:

"([0-9][0-9]?[0-9]?[0-9]?[0-9]?(\.)?([0-9]?[0-9]?))"

That is, the former is required, and the following 4 are optional. However, I have some suggestions for improving this regex:

  • Use the keys to choose the number of times an element will repeat itself. exp{n} means that the expression must occur exactly n times. exp{a,b} means that it needs to occur at least a and at most b times:

    "([0-9]{1,5}(\.)?([0-9]{0,2}))"
    
  • If these groups are not capture, I suggest removing them, as this unnecessarily complicates regex:

    "[0-9]{1,5}\.?[0-9]{0,2}"
    
  • This is still possible to have a point with no digits in front, or no point and two digits too long. Connect the dot to the digits, and require at least 1 digit if the dot is present:

    "[0-9]{1,5}(\.[0-9]{1,2})?"
    
  • You can use \d (escaped, \d ) to represent a digit instead of the [0-9] range:

    "\d{1,5}(\.\d{1,2})?"
    
  • If you want to avoid zeros on the left, separate the case from 0 with the case of [1-9] followed by 0 to 4 digits:

    "(0|([1-9]\d{0,4}))(\.\d{1,2})?"
    
  • 06.12.2015 / 02:40
    0

    I suppose it can satisfy you: /^(\d{1,5})?(\.\d{1,2})?$/

    Here dry an example in% with% of validation:

    $('input').keyup(function(e){
      var val = this.value;
      var test = /^(\d{1,5})?(\.\d{1,2})?$/
      
      if(test.test(val)){
        $("p").html("Válido.")
      }else{
        $("p").html("Inválido.")
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><inputtype="text" value="12345.67"/><br>
    <p></p>
        
    05.12.2015 / 00:14