i have this code(works fine) that changes the color of all fields wheather the field is empty or not:
document.querySelectorAll("input").forEach((inp) => { inp.addEventListener("focusout", () => { let value = inp.value.split(" ").join(""); if (value == "") inp.style.backgroundColor = 'red'; else inp.style.backgroundColor = 'green'; }); }); Now i want to validate the first name field, it should only be able to input letters. If it is wrong, i want it to show it as red. i tried with the following code but it doesnt work. Any ideas?
let firstName = document.querySelector("#fname"); firstName.addEventListener("focusout", () => { if (typeof firstName.value != "string") { firstName.value.style.backgroundColor = "red"; console.log(firstName.value); } else { firstName.value.style.backgroundColor = "green"; } });