2
What is the error of this regular expression. I have tried it with another function and the mask works. But this one for pennies, it doesn’t work. What’s the mistake?
<html>
<body>
<script>
function mascara(o, f) {
obj=o;
fun=f;
setTimeout(execMascara(), 1);
}
function execMascara() {
obj.value=fun(obj.value);
}
function soNumeros(v) {
var v = this;
if(v.indexOf('.')==-1) {
v = v.replace(/([\d]+)/, "$1,00");
}
v = v.replace(/([\d]+)\.([\d]{1})/g, "$1,$20");
v = v.replace(/([\d]+)\.([\d]{2})/g, "$1,$2");
return v ? "R$ " + v : 'Grátis';
}
</script>
<form>
<label="numero">
Só número: <input id="numero" onkeypress="mascara(this,soNumeros)"/>
</label>
</form>
</body>
</html>
<html>
<body>
<script>
function mascara(o, f) {
obj=o;
fun=f;
setTimeout(execMascara(), 1);
}
function execMascara() {
obj.value=fun(obj.value);
}
function soNumeros(v) {
var v = this;
if(v.indexOf('.')==-1) {
v = v.replace(/([\d]+)/, "$1,00");
}
v = v.replace(/([\d]+)\.([\d]{1})/g, "$1,$20");
v = v.replace(/([\d]+)\.([\d]{2})/g, "$1,$2");
return v ? "R$ " + v : 'Grátis';
}
</script>
<form>
<label="numero">
Só número: <input id="numero" onkeypress="mascara(this,soNumeros)"/>
</label>
</form>
</body>
</html>
@rray has already been formatted. I’m still interacting with stackoverflow formatting.
– André Nascimento
Remove the . exhaust from both regex, tested without them and worked normally.
– user28595
@Diego Felipe is to take out the symbols "" and "."? I took out the "" and continues accepting letters.
– André Nascimento
Look at @Brunno’s reply, it fits perfectly to what you want to do.
– user28595
@Diego Felipe Vi, but has a situation, I commented there. The user needs to enter 00 to enter values only in real. If you do not enter 00, the value is changed.
– André Nascimento
I see no problem in it, if you check big internet bankings, these digits work this way, you type and need to add zeros to "grow" a value. As long as the mask shows the user that if they type 120, it will format as 1.20 before (as in the Runner solution), it is no problem. One should pay attention to the case that it turns off javascript, but I believe that a confirmation screen would be enough.
– user28595
@Diego Felipe true. I will use so and make a note in the form for the user.
– André Nascimento