Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda