Home > OS >  Allow typing minus sign at the start of a number during live input validation of integer or float of
Allow typing minus sign at the start of a number during live input validation of integer or float of

Time:01-28

I want to allow user to input decimal value with maximim 9 integer digits, and maximum 2 decimals after dot. But also this value can be negative, with "-" sign. Evereything is ok, except this minus sign. Though sites like "regexp.online" show that my regular expression is fine, it does no work in js jquery. Minus sign fails the checking. See:

$('[name="price"]').bind("change keyup input", function() {
  pricecheck = '^(\\-)?\\d{1,9}(\\.\\d{0,2})?$';
  var regex = new RegExp(pricecheck, 'g');
  if (!regex.test(this.value)) {
    console.log('not in regex');
    this.value = this.value.slice(0, -1);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="price" style="height:20px;">

And fiddle - https://jsfiddle.net/obc6qptf/

I tried this "minus" without backslashes - the same result. What is wrong?

CodePudding user response:

You need to use a regex that will match the first digit optionally:

const regex = /^-?\d{0,9}(?:\b\.\d{0,2})?$/;

Note the \b word boundary is used to make sure the . separator does not come right after -, and if you need that, remove \b from the pattern.

Details:

  • ^ - start of string
  • -? - a - char (optional)
  • \d{0,9} - zero to nine digits
  • (?:\b\.\d{0,2})? - an optional sequence of
    • \b - a word boundary to require a digit (here) before .
    • \. - a dot
    • \d{0,2} - zero, one or two digits
  • $ - end of string.

See the JavaScript demo:

$('[name="price"]').bind("change keyup input", function() {
  const regex = /^-?\d{0,9}(?:\b\.\d{0,2})?$/;
  if (!regex.test(this.value)) {
    this.value = this.value.slice(0, -1);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="price" style="height:20px;">

  •  Tags:  
  • Related