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

307
Visualizações
Allow Only Numbers and a Dot in the following Format with Regex javascript/jquery

I have an input field which should get filled by the user with only numbers and a singel dot/comma and only in the following format.
This should occure .on("input") meaning as the user types it should secure the right input format.

A wrong char should be replaced with a blank.

Format Example:
1.000
1.281
21212.000
21212.810
Nothing like this:
1.02.12
or
1919,201,00
Only a dot between the two Number blocks.

This is what i have so far:

Regex 1:

$("body").on("input", "#testId", function(){
     this.value = this.value.replace(/[^0-9]/g,'');
});

Regex 2:

$("body").on("input", "#testId", function(){
     this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});

Regex 3:

$("body").on("input", "#testId", function(){
     this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});

I think i am doing something wrong with the replace() method. Unfortunately none of them work as i want to. Any help is appreciated.

Here is the FIDDLE

Should Work in IE11

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can try this. make sure your input type is tel which will allow you to have numeric keypad in mobile browser

const regex = /[^\d.]|\.(?=.*\.)/g;
const subst=``;



$('#testId').keyup(function(){
const str=this.value;
const result = str.replace(regex, subst);
this.value=result;

});
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<input id="testId" type="tel" />

</body>
</html>

about 4 years ago · Santiago Trujillo Relatório

0

try this one,

^[0-9]*(\.|,)?[0-9]*$

this take below cases:

1111, .0000 123,12 12.12 12345

but if you want only

111,11 11.11 12345

so please use this

^[0-9]+(\.|,)?[0-9]+$

to force use dot/comma please use this

^[0-9]+(\.|,)[0-9]+$

add this code

$("#testId").keyup(function(){

   var vals = $("#testId").val(); 

   if(/^[0-9]*(\.|,)?[0-9]*$/g.test(vals))
    $("#testId").val(vals);
     else
    vals = vals.replace(/.$/,"");

    $("#testId").val(vals);
  });

and change input type to

type="text"

about 4 years ago · Santiago Trujillo 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