简体   繁体   中英

Validation in JavaScript - how to make the red border disappear?

At the moment, when a field is empty and not valid the field turns red and a describing text shows up. But how do I make the field and text disappear when the user fill in the field correctly?

code in HTML:

<label for="email"><b>Email</b></label>
        <label id="lblemail" style="color: red; visibility: hidden; float: right;">Invalid email</label><br>
        <input type="text" placeholder="Enter Email" name="email" id="email"><br>

code in JS:

var email = document.getElementById("email");

if (email.value.trim() == "") {
    email.style.border = "solid 1px red"
    document.getElementById("lblemail").style.visibility="visible";
    return false;
} else {
  return true; }

You should add event listener on input event:

const email = document.getElementById('email');
const label =  document.getElementById('lblemail');

email.addEventListener('input', function(e) {
  if (!e.target.value.trim()) {
    email.style.border = 'solid 1px red';
    label.style.visibility = 'visible';
  } else {
    email.style.border = 'solid 1px black';
    label.style.visibility = 'hidden';
  }
})

It's better to use input event because it checks input each time you change it

I think you can unset using js code

var email = document.getElementById("email");

if (email.value.trim() == "") {
    email.style.border = "solid 1px red"
    document.getElementById("lblemail").style.visibility="visible";
    return false;
} else {
    email.style.border = "none"
    document.getElementById("lblemail").style.visibility="hidden";
  return true; 
}

i think you can use a eventlistener, this should work

var email = document.getElementById("email");

email.addEventListener('change', () => {
 if (email.value.trim() == "") {
     email.style.border = "solid 1px red"
     document.getElementById("lblemail").style.visibility="visible";
     return false;
 } else {
   email.style.border = none;
   document.getElementById("lblemail").style.visibility="visible";
   return true; }

})


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM