Simplify value comparison on an input

Asked

Viewed 103 times

0

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 was the same as: "Jose", "maria" or "Joao".

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

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

It is possible instead of repeating campo.val() == "NOME" ||... for each name, make a more simplified comparison, without having to keep repeating campo.val() == for each name only on if, without using array or other subterfuge outside the function?

2 answers

4


A good way to make that comparison is with array but since you don’t want to believe that 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>
<input id="nome" name="nome" type="text" onchange="valida()" />

Take a look at this website.

  • 1

    Ball show! Obg!

2

That 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");
}
  • I would not like to use array for this. I would like a simplified comparison mode in if.

Browser other questions tagged

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