zik
zik

Reputation: 3085

Am I using the isNAN function in JavasScript correctly here?

I've got a form where the user inputs 3 values, which are then calculated. The outputs are displayed again within the form in some "readonly" output boxes. For each input, I want to validate if they are a number, if not, instead of the form showing "NaN" I want to display an error saying, "Please enter a number" (or something like that). Below is the code I am using, which is executed "onkeyup":

function checkforNumber() 
{
    if (isNaN(sInput || dInput || pInput) == true) {
        alert("You entered an invalid character. Please reset the form.");
    }
    else {
        return(false);
    }
} 

Am I using this function incorrectly? Is there something wrong with the syntax?

Thanks

Upvotes: 1

Views: 360

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput)) {
    alert("You entered an invalid character. Please reset the form.");
}

also make sure that those 3 variables sInput, dInput and pInput are not strings but were obtained by using parseFloat or parseInt methods.

var sInput = parseFloat(document.getElementById('sinput').value);
var dInput = parseFloat(document.getElementById('dinput').value);
var pInput = parseFloat(document.getElementById('pinput').value);

Upvotes: 3

James Allardice
James Allardice

Reputation: 166001

if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput))

This is what I think you intended. You need to pass each value you want to test in to the isNaN function one at a time. Also note that you don't need the == true part, because isNaN returns true or false so the condition will evaluate to the return value.

Upvotes: 1

Related Questions