Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is wrong with this if condition in Javascript?

What is wrong with this IF condition? When I am giving EEID value as 123456 it should not come into this condition. But I see that it is coming. Can somebody let me know what am I doing wrong?

if ((EEID.value.length != 6) || (EEID.value.length != 11)) {
        alert(EEID.value.length); //This shows that the value length = 6
        alert("Your Member ID must be a 6 digit or 11 digit number.");
        EEID.focus();
        return false;
      }
like image 350
Ditty Avatar asked Dec 19 '12 17:12

Ditty


2 Answers

The condition is satisfied because EEID.value.length is not 11. The or (||) allows either != 6 or != 11 to satisfy the if condition.

You need to change the or (||) to an and (&&) as such:

if ((EEID.value.length != 6) && (EEID.value.length != 11)) {
    alert(EEID.value.length);
    alert("Your Member ID must be a 6 digit or 11 digit number.");
    EEID.focus();
    return false;
}

This way, the if condition is satisfied only when EEID.value.length is not 6 and not 11.

like image 186
Fls'Zen Avatar answered Sep 23 '22 11:09

Fls'Zen


What you originally have, (!P || !Q), returns true all the time, as EEID.value.length cannot be both 6 and 11 at the same time. When one is false, the other is true, and vice versa, thus it is always true.

Take a look at De Morgan's laws, or more precisely that

(!P && !Q) == !(P || Q)

Which is similar to what you have, but states that the condition is true if EEID.value.length is neither 6 or 11. (Note that I would prefer the right side as it only negates once.) So, basically, you can write your conditions like

if ((EEID.value.length != 6) && (EEID.value.length != 11)) {

or

if (!(EEID.value.length == 6 || EEID.value.length == 11)) {
like image 27
Yanick Rochon Avatar answered Sep 22 '22 11:09

Yanick Rochon