Search code examples
javascriptformsvalidationif-statementtypeof

Checking input type in JS


I'm using the typeof command to make sure that only 1 of the 2 input fields of this temperature (Celsius to/from Fahrenheit) calculator is populated with data and it has to be a number. If the input is not a valid number or both fields are populated, the app will throw an error message.

The problem: nothing satisfies this condition - the errorMessage is always shown, even if I type in a valid number.

Is typeof the right solution to this problem? If it is, why is this code not working?

document.getElementById('temperature-form').addEventListener('submit', calculateResult);

function calculateResult(e) {
    e.preventDefault();
    const celsiusInput = document.getElementById('celsius');
    const fahrenheitInput = document.getElementById('fahrenheit');
    let resultOutput = document.getElementById('result');
    // validate input data type and calculate result  
    if ((typeof celsiusInput === 'number') && (fahrenheitInput === null)) { 
        resultOutput.value = (celsiusInput.value * 1.8 + 32) + ' Fahrenheit';
    } else if ((celsiusInput === null) && (typeof fahrenheitInput === 'number')) {
        resultOutput.value = ((fahrenheitInput.value - 32)/1.8) + ' Celsius';  
    } else {
        errorMessage('Please add a number in one of these fields');
    } 
}

Many thanks!


Solution

  • You could check the value properties of each input to see if they are numbers using the isNaN() function like so:

    function calculateResult(e) {
        e.preventDefault();
        //Get the value of each input box
        const celsiusValue = document.getElementById('celsius').value;
        const fahrenheitValue = document.getElementById('fahrenheit').value;
        //Get the result element
        let resultOutput = document.getElementById('result');
    
        // validate input data type and calculate result  
        if(!isNaN(celsiusValue) && (fahrenheitValue === null || fahrenheitValue === "")){
            //Only celsiusValue has a valid number
            resultOutput.value = (celsiusValue * 1.8 + 32) + ' Fahrenheit';
        }else if(!isNaN(fahrenheitValue ) && (celsiusValue === null || celsiusValue === "")){
            //Only fahrenheitValue has a valid number
            resultOutput.value = ((fahrenheitValue - 32)/1.8) + ' Celsius';  
        }else if(!isNan(celsiusValue) && !isNan(fahrenheitValue )){
           //Both contain a valid number
           //Figure this one out as you didn't account for it
        }else{
           //Neither is a valid number
           errorMessage('Please add a number in one of these fields');
        } 
    }
    

    Documentation of isNaN(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN