Course contentsShow
← Web Development
Lesson 109 of 2,9822. HTML FundamentalsFree lesson

Form Validation Attributes and :invalid

Understanding native HTML5 validation states and styling invalid inputs with CSS pseudo-classes.

Form Validation Attributes and :invalid

You'll learn how to use CSS to visually highlight form fields that fail HTML5 validation rules.


When you add validation attributes like required, pattern, min, or maxlength to form inputs, the browser automatically checks whether the user's input meets those rules. But how do you show the user when something's wrong? That's where the :invalid CSS pseudo-class comes in.

What is :invalid?

The :invalid pseudo-class is a special CSS selector that targets any form field currently failing validation. Think of it like a traffic light: when a field breaks the rules you set with HTML attributes, the browser flips an internal switch to "invalid," and your CSS can respond to that state.

How It Works

Imagine you have an email input with required and type="email". If the field is empty or contains text without an @ symbol, the browser marks it as invalid. You can style it:

input:invalid {
  border: 2px solid red;
}

Now any invalid input gets a red border automatically—no JavaScript needed!

The Valid Counterpart

There's also :valid for fields that pass validation:

input:valid {
  border: 2px solid green;
}

Combining with HTML Attributes

This works seamlessly with all the validation attributes you've learned: required, pattern, min, max, minlength, maxlength, and input types like email or url.

<input type="email" required>
input[type="email"]:invalid {
  background-color: #ffe6e6;
}

Key Takeaway: The :invalid pseudo-class lets you style form fields that fail HTML5 validation, giving users instant visual feedback without writing JavaScript.