Validation failed

1

I am writing a function to validate only numbers in one case and only letters in another, however, when I only had one function to validateNumbers, the function worked fine, when I have both at the same time, both go wrong.

function somenteNumeros(num) {
        var er = /[^0-9]/;
        er.lastIndex = 0;
        var campo = num;
        if (er.test(campo.value)) {
            campo.value = "";
        }
    }
    function somenteLetras(letra) {
        var er = /[^a-zA-Z]/s;
        er.lastIndex = 0;
        var campo = letra;
        if(er.test(campo.value)){
            campo.value = "";
        }
    }

<input type="text" size="35" name="nomeOutro" onkeyup="somenteLetras(this)" minlength="3" maxlength="150"/>

<input type="text" size="1" name="idade" onkeyup="somenteNumeros(this)" maxlength="3"/>
    
asked by anonymous 23.11.2016 / 23:14

1 answer

1

In JavaScript there is no s flag in RegExp. Take and it will work as you want:

var er = /[^a-zA-Z\s]/; 

jsFiddle: link

You could simplify logic and have only one function ... like this:

function valida(el, regex) {
    if (regex.test(el.value)) {
        el.value = "";
    }
}
<input type="text" size="35" name="nomeOutro" onkeyup="valida(this, /[^a-zA-Z\s]/)" minlength="3" maxlength="150" />
<input type="text" size="1" name="idade" onkeyup="valida(this, /[^0-9]/)" maxlength="3" />
    
23.11.2016 / 23:22