Failed validation

Asked

Viewed 32 times

1

I’m writing a Function to validate only numbers in one case and only letters in another, however, when I only had a Function to validate Noughts, Function worked, 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"/>

1 answer

1


In Javascript there is no flag s in Regexp. Strip and will already work as you want:

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

jsFiddle: https://jsfiddle.net/xs6hj5LL/

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" />

  • How can I leave allowed space then ?

  • @Caiovieira I added this possibility in the answer.

  • 1

    It worked, thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.