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?
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
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.
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}" />