What is the error in this regular expression?

2

What is the error of this regular expression. I already tested it with another function and the mask works. But this one for numbers with cents, does not work. What is the error?

<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>
    
asked by anonymous 20.10.2015 / 16:24

2 answers

2

The object window is overwriting the value entered in the text field, see line 16.

var v = this; //Está instrução não faz muito sentido

The object window does not have the function indexOf() .

    
20.10.2015 / 16:50
2

To add the mascara only with JavaScript and Regex, I would do the following:

document.getElementById('numero').addEventListener("keyup", mascara); //Pego evento de keyup ()

function mascara() {
    var v = this.value; //Pego valor
    v = v.replace(/\D/g, ''); //Valida se é numero
    v = v.replace(/(\d{2})$/, ',$1'); //Seto valores antes da virgula
    v = v.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.');
    this.value = v != '' ? 'R$ ' + v : 'Grátis'; //Retorno seu valor com (R$) ou se estiver vazio seta para (Grátis) :D 
}

Follow a jsfiddle of the mascara:)

    
20.10.2015 / 17:14