For a user friendly interface, it's usually best to validate based on the actual value of the input, so don't use charCode, use the input's value. For that a simple regular expression suits:
if (/\D/.test(value)) {
// a non–digit was entered
}
It's often best to validate when the user is finished with the input, e.g. for banking I might copy and paste the balance of my credit card as "1,203.43" and then remove the comma. Then the field is validated when I leave it (onblur or onsubmit) with a suitable onscreen message, leaving me to fix it if it's wrong.
But in some cases it also suits to use keyup or some other suitable event.
So in the case of an input that should have digits only, you might do something like the following:
function validate(el) {
if (el.classList.contains('numsOnly')) {
document.getElementById(el.id + 'Err').innerHTML = /\D/.test(el.value)? "Must contain only digits" : '';
}
}
.screenHint {font: sans-serif; font-size: 80%; color: #999999}
<label for="aNum">A number:<input name="aNum" id="aNum" class="numsOnly"
onblur="validate(this)" onkeyup="validate(this)" onpaste="validate(this)"
placeholder="1234"></label><span class="screenHint">Digits only</span><br>
<span style="color:red; background-color: white;" id="aNumErr"></span>
Of course you would likely add the listeners dynamically and have a much more extensive set of validations but the above shows some of the principles.