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

77
Visualizações
How to replace an input text value in order to match a currency type input

I have a complex problem with a simple input. I want the user to enter an amount of money, so I naturally thought of using a number type. The problem is that I live in Europe and decimals are written with commas(and so the number input will automatically add a comma as separator), but my backend logic expects dots for the cents.

After looking everywhere for alternatives to this problem, I only found I could use a text input and check the user's input with a chain of .replace to test that the user is only entering numbers and eventually a dot followed by only two numbers for the cents.

This is the code we created so far:

export const onChangeCustomInput = (e) => {
    let value = e.target.value

    value = value
        .replace(/[A-Za-z]+$/g, '')
        .replace(/,/g, '.')
        .replace(/ /g, '')
        .replace(/\B(?=(\d{3})+(?!\d))/g, ' ')
        .replace(/[.\s]{2,}/, '.')
        .split('.')

    if (typeof value === 'object' && value.length > 1) {
        value[1] = value[1].substr(0, 2)

        if (value.length === 3) {
            value.splice(2, 1)
        }

        value = value.join('.')
    }

    e.target.value = typeof value === 'object' ? value[0] : value
}

this is very heavy (and ugly) code, and Sonar check failed saying this may lead to Denial of Service attack (?...).

Is there a better way to manage this case in vanilla javascript?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Can you try toLocaleString?

Basically if you have a number You can set in which kind of country you're using it.

So, you can show as an EU number, but send to the backend in the other format.

One example:

var number = 35001235.12
number.toLocaleString('en-US') // returns '35,001,235.12'

number.toLocaleString('de-De') // returns '35.001.235,12'

You can read more in: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

about 4 years ago · Juan Pablo Isaza Relatório

0

You could try using valueAsNumber property of the input element. The value is numeric so it shouldn't matter what was entered by the user. If the input is wrong it takes the value of NaN.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use the package Inputmask, it works perfect for your use case, you will use this regex [0-9]*\.[0-9]{2} to match your example

$(document).ready(function(){
  Inputmask().mask(document.querySelectorAll("input"));
});
<script src="https://code.jquery.com/jquery-1.10.0.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/jquery.inputmask.js"></script>

<input  data-inputmask-regex="[0-9]*\.[0-9]{2}" />

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