CSS :valid
The :valid pseudo-class in CSS is used to select input elements that contain valid data according to the specified rules. It is commonly used with form elements to give visual feedback to the user based on their input.
In this tutorial, we will create a simple form that utilizes the :valid pseudo-class to highlight valid input fields. We will be working with a fictional registration form that includes fields for a username and an email address.
<form>
<label for="username">Username:</label>
<input type="text" id="username" pattern=".{3,}" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" required>
<br>
<input type="submit" value="Register">
</form>
<style>
input:valid {
border: 2px solid green;
}
input:invalid {
border: 2px solid red;
}
</style>
In this example, we have created a form with two input fields: one for the username and another for the email. The username field requires a minimum of 3 characters, while the email field requires a valid email format.
When an input field is considered valid, its border color will change to green. Conversely, if it is invalid, the border color will change to red. This visual feedback helps users understand if their input meets the required criteria.
Feel free to try entering different values into the fields above. For instance, a username with fewer than 3 characters will trigger the :invalid style, making the border red. Once a valid username and email are entered, the border will change to green, indicating that the inputs are valid.