0

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"; } }); 
3
  • The value will always be a string, even if it's an empty one. Commented Jul 29, 2021 at 12:50
  • even when i input a number it doesnt work Commented Jul 29, 2021 at 12:52
  • Because the value will always be a string, even if it's a number. Commented Jul 29, 2021 at 12:57

2 Answers 2

1

You could use a Regex to check if string has number. Something like:

let firstName = document.querySelector("#fname"); firstName.addEventListener("focusout", () => { let hasNumber = /\d/; if (hasNumber.test(firstName.value)) { firstName.value.style.backgroundColor = "red"; console.log(firstName.value); } else { firstName.value.style.backgroundColor = "green"; } }); 
Sign up to request clarification or add additional context in comments.

Comments

0

value will always be a string so you should test what characters the string contains instead, and you can do this with a regular expression that tests that it only contains letters from the alphabet.

let firstName = document.querySelector("#fname"); firstName.addEventListener("focusout", () => { if (!/[a-zA-Z]+/.test(firstName.value)) { firstName.style.backgroundColor = "#FF374E"; } else { firstName.style.backgroundColor = "#c0eb34"; } });
<input id="fname" />

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.