I'm having some problems creating the mask for the currency field.
1- I need to limit UP TO 18 characters (counting the '.' and the ',') Ex: 999.999.999.999,99
2 - I need you to put more than one '.' (currently only one)
3 - I need this not to happen:
Because when I type it adds the '.' right then before I type in one more number.
My code:
function onlyNumberAmount(input) {
var v = input.value;
v = v + '';
v = parseInt(v.replace(/[\D]+/g, ''));
v = v + '';
v = v.replace(/([0-9]{2})$/g, ",$1");
v = v.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");
input.value = v;
if(v == 'NaN') input.value = '';
}
<input type="text" class="form-control" id="mP0" onkeyup="onlyNumberAmount(this)">
The following seems to meet your requirements.
function onlyNumberAmount(input) {
let v = input.value.replace(/\D+/g, '');
if (v.length > 14) v = v.slice(0, 14);
input.value =
v.replace(/(\d)(\d\d)$/, "$1,$2")
.replace(/(^\d{1,3}|\d{3})(?=(?:\d{3})+(?:,|$))/g, '$1.');
}
<input type="text" class="form-control" id="mP0" onkeyup="onlyNumberAmount(this)">
\d is short for [0-9] as I'm sure you know.
A positive lookahead (?=(?:\d{3})+(?:,|$)) is used to ensure the correct placement of the .
14 is the maximum number of digits that can appear in the string.
Further explanation on request.
If, test if the field is already valid
const moneyTest = /(\d{1,3}\.)?(\d{1,3}\.)?(\d{1,3})?(.\d{1,2})?/
if (!moneyTest.test(field)) {
Then, if it's not, separate into the number fields
var digits = /d/g.match(field); // might be field.match(/d/g)
Now you have to see if there was a decimal place in the original number
var dot = field.lastIndexOf(".");
And then you should be good to reconstruct the number.
Question: What happens if there are two dots?