Remove previously set border color

The problem is the colors have the same level of importance to css and therefore the code does not know which one to prioritize. So, to fix that, you have to make the green more important in the css code.

To do that change the focus css code to look like this.

#username:focus {
  background-color: yellow !important;
  border-color: green !important;
}

#password:focus {
  background-color: yellow !important;
  border-color: green !important;
}

#message {
  color: red;
}

Hope this helps!


This is happening because you have updated the element style instead of CSS class property. Element style has the highest weight for CSS. Instead add an error class dynamically on error and remove it when the form field is valid.

As per the documentation, the order of style in decreasing order will be.

  1. Inline style (inside an HTML element)
  2. External and internal style sheets (in the head section)
  3. Browser default

Here is a working example

function validate() {
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;

    if (username == "") {
        document.getElementById("message").innerHTML = "USERNAME CANNOT BE EMPTY";
        document.getElementById("username").classList.add("invalidInput");
        return false;
    } else {
        document.getElementById("username").classList.remove("invalidInput")
    }
    if (password == "") {
        document.getElementById("message").innerHTML = "PASSWORD CANNOT BE EMPTY";
        document.getElementById("password").classList.add("invalidInput")
        return false;
    } else {
        document.getElementById("password").classList.remove("invalidInput")
    }
}
#username:focus {
    background-color: yellow;
    border-color: green;
}

#password:focus {
    background-color: yellow;
    border-color: green;
}

.invalidInput {
    border-color: red; 
}

#message {
    color: red;
}
<form onsubmit=" return validate()">
    LOGIN:-
    <br />
    <input id="username" type="text" name="username" placeholder="USERNAME" />
    <br />
    <input id="password" type="password" name="password" placeholder="PASSWORD" />
    <br />
    <input type="submit" value="SUBMIT" />
    <p id="message"></p>
</form>