skip to Main Content

I am trying to validate an input field so that it only accepts numbers.

When I try to validate an input such as ‘123’ it works as expected, however when I validate an input such as ‘123abc’ it does not work and ‘123abc’ gets accepted as a number.

Could any please explain to me why and what to do about it?

My code is in the following codepen link: https://codepen.io/npinak/pen/dygNEOW?editors=1011

// get the operator button class
const operators = Array.from(document.getElementsByClassName('operator'))

// add function to each button
operators.forEach((operator) => {
    operator.addEventListener('click', mathOperation)
})

// values from input fields
const inputs = Array.from(document.getElementsByClassName('input'))

// check for blank inputs 
function blankInput(e){

    const textValue = e.target.value
    const allSpacesRemoved = textValue.replace(/ /g, '');
    const allSpacesRemovedFloat = parseFloat(allSpacesRemoved)
    
    if (allSpacesRemovedFloat === ''){
        e.target.classList.add('noInput')
    } else if (Number.isNaN(allSpacesRemovedFloat) === true){
        console.log(Number.isNaN(allSpacesRemovedFloat))
        e.target.classList.add('noInput')
    } else {
        e.target.classList.remove('noInput')
    }
}

console.log(inputs[0])

inputs.forEach((input) => {
    input.addEventListener('blur', blankInput)
})


function mathOperation(e){

    e.preventDefault()
    // get header for result
    const result = document.getElementById("result")

    // convert values from input to float
    const value1 = parseFloat(inputs[0].value)
    const value2 = parseFloat(inputs[1].value)

    //check if value1 and value2 are numbers
    if (Number.isNaN(value1) || Number.isNaN(value2)){
        window.alert("Please enter a valid input.")
        
        // get input element

        // add .inputVisible class

        // remove .inputVisible class after 3 seconds 
        return 
    }

    // math operation
    if(e.srcElement.id === 'division'){
        const finalValue = value1 / value2
        result.innerText = finalValue
    } else if (e.srcElement.id === 'multiplication') {
        const finalValue = value1 * value2
        result.innerText = finalValue
    } else if (e.srcElement.id === 'subtraction') {
        const finalValue = value1 - value2
        result.innerText = finalValue
    } else if (e.srcElement.id === 'addition') {
        const finalValue = value1 + value2
        result.innerText = finalValue
    }
}```

2

Answers


  1. The issue is that parseFloat will try to convert as much of the string as possible, stopping when it reaches an invalid character. parseFloat('123abc') produces 123 as the result.

    You can directly check isNaN on the string before parsing instead.

    else if (isNaN(allSpacesRemoved)) {
    

    Alternatively, you could use a regular expression for more precise validation.

    Login or Signup to reply.
  2. You are using parseFloat in your attempt to validate the value as a number. See the documentation on MDN:

    parseFloat() picks the longest substring starting from the beginning that generates a valid number literal. If it encounters an invalid character, it returns the number represented up to that point, ignoring the invalid character and all characters following it.

    123 starts at the beginning and it a valid number literal.

    Adding a would make it invalid, so everything from that point is ignored.

    So it is behaving as designed.


    See How can I check if a string is a valid number? for methods to achieve your goal.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search