Reputation: 89
My if statement evaluates only 1st condition, second one after || is overlooked. How to fix this?
function validateAge(input) {
if ((input.value < 0 || input.value > 110) || (input.value.match(/[^0-9]/))) {
input.setCustomValidity("Dozwolony zakres: od 0 do 110");
} else {
input.setCustomValidity("");
}
}
Upvotes: 2
Views: 2538
Reputation: 25682
Well, there is something called lazy evaluation. The JavaScript interpreter won't evaluate something if it is unnecessary to do so. In the disjunction (||
) when the first statement evaluates to true
then the whole expression is true, so that's why when the JavaScript interpreter evaluates: (input.value < 0 || input.value > 110)
to true, it is not necessary to calculate the value of (input.value < 0 || input.value > 110)
.
If (input.value.match(/[^0-9]/))
is "show stopper" you can proceed the following way:
if ((input.value.match(/[^0-9]/)) || (input.value < 0 || input.value > 110))
If I understood correctly you need something like:
function validateValue(input) {
var value = input.value;
if (/^\d+$/.test(value)) {
value = parseInt(value, 10);
} else {
return false;
}
return value < 0 || value > 110;
}
Upvotes: 7