Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
Allow typing minus sign at the start of a number during live input validation of integer or float of specific length with up to two decimal digits

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;">

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!