I'm building a registration form with alphabetical input only, and regardless of whether I input an alphabetical or special character, my error message still appears. As it stands, I thought my code would search through the value in fname
, and if it doesn't match the characters in ABC
, then it should return FALSE
and create my error message at the bottom (except my error message appears even when I input an alphabetical character, which I thought should output TRUE
and not execute the IF
statement).
What am I doing wrong?
// First Name & Last Name Validation
let fname = document.getElementById("fname");
fname.addEventListener("keypress", ABCvalidate);
let ABC = /^[A-Za-z]+$/;
function ABCvalidate() {
if (!ABC.test(fname.value)) {
document.getElementById("CSerror").innerHTML =
"No spaces or special characters allowed";
}
}
Some of the issues i see
keypress
event is deprecatedfalse
)You can use the input
event which will also handle copy/pastes in to the input element.
// First Name & Last Name Validation
let fname = document.getElementById("fname");
fname.addEventListener("input", ABCvalidate);
let ABC = /^[A-Za-z]+$/;
function ABCvalidate() {
const errorElement = document.getElementById("CSerror");
if (!ABC.test(fname.value)) {
errorElement.innerHTML = "No spaces or special characters allowed";
} else {
errorElement.innerHTML = '';
}
}
<input id="fname" />
<div id="CSerror"></div>