Search code examples
javascripthtmlalgorithmlogic

elegant way to filter out non numeric input


if (input >= 0 && input <= 100 ) {}

The variable input is directly filled with the content of an inputfield. I do not only wish to only get input in the specific arange but als only numbers. How can i extend the condition on top that it only accepts numbers as input and not for example the input a?


Solution

  • You can make sure it's a number first, with something like

    const parsedInput = parseInt(input);
    if (!isNaN(parsedInput) && parsedInput >= 0 && parsedInput <= 100) { }
    

    Once you parsed the input, you can verify if is not isNaN where NaN stands for "Not a Number".

    You need to parse it first because isNaN tries to convert the number, so that isNaN('10') returns true. If you parse it first with parseInt, you're good to go :)

    Otherwise without parsing it you might have a string in that variable. Javascript is dummy and still evaluates '10' >= 0 as true, but if you can enforce to have a number is better.