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
}
}```