Eljano Hita
Eljano Hita

Reputation: 7

Javascript change input field color

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";
  }
});

Upvotes: 0

Views: 42

Answers (2)

Andy
Andy

Reputation: 63524

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" />

Upvotes: 0

Giovanni Esposito
Giovanni Esposito

Reputation: 11156

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";
  }
});

Upvotes: 1

Related Questions