How to modify input field border colors for focus and validation states?

Hi everyone! I’m working on a login page and I want to make the input fields behave like those on popular email services. Here’s what I’m trying to do:

  1. When the user focuses on an input field, I want the border to turn blue.
  2. If the user enters invalid data, the border should change to red.

I’m not sure how to achieve this effect. Can anyone share some CSS or JavaScript tips to make this work? I’ve tried a few things but can’t seem to get it right. Any help would be awesome!

Here’s a basic example of what I have so far:

<input type="text" id="username" placeholder="Username">
<input type="password" id="password" placeholder="Password">
input {
  border: 1px solid #ccc;
}

input:focus {
  /* What should I put here? */
}

input.error {
  /* And here for invalid input? */
}

Thanks in advance for your help!

I’ve implemented something similar recently, and here’s what worked well for me:

For the focus state, you can use the :focus pseudo-class in CSS. To change the border color when focused, try this:

input:focus {
border-color: blue;
outline: none; /* Removes default focus outline */
}

For validation, you’ll need some JavaScript. Add an event listener to your input fields that checks the input value on blur (when the user clicks away). If it’s invalid, add an ‘error’ class to the input. Then in your CSS:

input.error {
border-color: red;
}

This approach gives you flexibility to define what ‘invalid’ means for each field. You could also use HTML5 form validation attributes like ‘required’ or ‘pattern’, and style the :invalid pseudo-class instead.

Remember to provide visual feedback beyond just color changes for accessibility. Maybe add an icon or error message for invalid inputs.

Here’s a practical approach I’ve used in my projects:

For the focus state, utilize the :focus pseudo-class in your CSS:

input:focus {
border-color: #3498db;
box-shadow: 0 0 5px rgba(52, 152, 219, 0.5);
}

This creates a subtle blue glow effect when focused.

For validation, combine CSS and JavaScript. Add a ‘data-valid’ attribute to your inputs:

Then use JavaScript to toggle this attribute based on your validation logic. In your CSS:

input[data-valid=“false”] {
border-color: #e74c3c;
}

This approach allows for easy styling changes and integrates well with most validation libraries.

hey there! for the focus state, try this:

input:focus {
border-color: #4285f4;
box-shadow: 0 0 0 2px rgba(66,133,244,0.3);
}

for validation, u can use js to add/remove a class:

input.invalid {
border-color: #d93025;
}

hope this helps! lemme know if u need more info :slight_smile: