Simplify value comparison in an input

1

I have a input on my form with id="nome" :

<input id="nome" name="nome" type="text" />

I would like the value of this input to be equal to: "jose", "maria" or "joao".

I have the following function to check if the value of input matches one of the names above:

function valida(){
    campo = $("#nome");
    if(campo.val() == "jose" || campo.val() == "maria" || campo.val() == "joao")
    {
        alert("Nome válido!");
    }else{
        alert("Nome inválido!");
    }
}

Is it possible, instead of repeating campo.val() == "NOME" ||... for each name, to make a more simplified comparison, without having to repeat campo.val() == for each name only in if , without using array or other subterfuge out of function?

    
asked by anonymous 17.11.2017 / 02:35

2 answers

4

A good way to do this comparison is with array itself, but since I do not want to believe the second option is by regular expression.

function valida(){
  campo = $("#nome");
  if(campo.val().match(/^(joao|jose|maria)$/))
  {
    alert("Nome válido!");
  } else {
    alert("Nome inválido!");
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><inputid="nome" name="nome" type="text" onchange="valida()" />

Take a look at this site .

    
17.11.2017 / 03:18
2

This should solve your problem:

var nomes = ["Everton", "Joao", "Rodrigo"];
var campo = $("#nome");
if (nomes.indexOf(campo.val()) > -1) {
   alert("Encontrou");
} else {
   alert("Não encontrou");
}
    
17.11.2017 / 03:03