Error javascript comparison operators

Asked

Viewed 68 times

-4

People have already done the test here and this variable returns true, even with the operands being equal, in this case was to return false and go jump into the else.

function testar(){
    var isOk =  /[A-Z][a-zA-Z][^#&<>\"~;$^%{}?]{1,20}$/;
    var nome = "Francisco";




    if(nome == ""){
        console.log("coloque o nome ")
    }else  if (nome != isOk.test(nome)){
        console.log("nome errado amiguinho");
    } else {
        console.log("ok vá em frente");
    }


}
  • 1

    You could be clearer?

  • The first if that has no sense. What you really wanted to test ?

  • isOk.text(nome) will return you or true, or false. Now, the variable nome is a string. true /*false?*/ != 'Francisco'. Soon he will always throw you in the "wrong name, little friend".

  • @Isac the first if as far as I understand it is to check if the field has been filled (if the input is == "" (empty string), ask to put the name)

  • @But it’s on top var nome = "Francisco";, which never gets into the first if . Unless this is an "example" and the name is read from somewhere other than what is in the question.

  • @Isac I believe is an example, he is probably just testing the logic before implementing, so much so that the "messages" in alerts are like validation for the user. It will probably be some kind of guessing game name.

Show 1 more comment

1 answer

1

I think what you want to do here is this:

    var isOk =  /[A-Z][a-zA-Z][^#&<>\"~;$^%{}?]{1,20}$/;
    var nome = prompt("Digite o nome:");

(function testar(){
    if(!nome) { //se não for digitado nada...
        console.log("coloque o nome ")
    }else  if (!isOk.test(nome)) { //se o nome NÃO bater com o regex...
        console.log("nome errado amiguinho");
    } else { //acertou!
        console.log("ok vá em frente");
    }
})();

On the line if(!nome), if the person does not enter any value, the value "" is considered false. The ! will reverse and make the same true, and run the code, asking it to type in something. If filled in any value inside, the filled string will hold as true, and to be reversed false, jumping into the else if.

In part else if (!isOk.test(nome)), the test will return true if the name entered is validated by regex, and then reversed by the exclamation. That is, if the name is NOT validated by regex, wrong answer. The last else will respond contrary to the previous if, ie if the name is correct.

There are better ways to do this, but I’ve edited your code as little as possible to make it functional.

Browser other questions tagged

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