AlienC
AlienC

Reputation: 31

Number Validation Not Working

I have an input field thats only supposed to take numbers inbetween 1 and 4. If the number is inbetween 1 and 4, it runs some code. If not, it shoots an alert that tells the user to try again with a number between 1 and 4. Here is my code

var number = document.getElementById("num").value;
     if(Number(number) === 1 || Number(number) === 2 || Number(number) === 3 || Number(number) === 4 ){
               //success code here///
             }
     else if(Number(number) !== 1 || Number(number) !== 2 || Number(number) !== 3 || Number(number) !== 4) { 
        }       alert("Please type a whole number between(and including) 1 and 4 into the input field.");

I learned that the '.value;' function returns a string, even if the value is a number. So I put the var 'number' in the Number(); function that converts it to a number. The problem is, when I type 1 into the input field. It shoots the alert even though it equals 1. None of the other numbers work either. I checked the console, and there are no syntax errors(also according to DreamWeaver). Help would be highly appreciated :)

Upvotes: 1

Views: 149

Answers (2)

Lokeswaraswamy Gubba
Lokeswaraswamy Gubba

Reputation: 56

we can write like this also

var patt1 = /[1-4]/g;
if(patt1.test(number)){
     //success code here///
}
else{
    alert("Please type a whole number between(and including) 1 and 4 into the input field.");
}

Upvotes: 0

xbakesx
xbakesx

Reputation: 13520

I think you made a simple mistake of putting your alert outside the else if clause.

However there are a few other things you can do to make that a little more readable and efficient.

// Call Number() here so you only have to do it once
var number = Number(document.getElementById("num").value);
// You can also do something like parseInt(document.getElementById("num").value)

// Now check to see if Number() or parseInt() actually parsed an integer out of their input
// and then check that if it's outside your number range
if (isNaN(number) || number < 1 || number > 4) {
    alert("Please type a whole number between(and including) 1 and 4 into the input field.");
} else {
    // Do Successful code
}

Upvotes: 1

Related Questions