:valid
selector - selects elements with a value that validates as per the element settings
:invalid
selector - selects elements with a value that won't validates as per the element settings
Both works on form input elements like
- Input elements with min & max are applied
- Email type input with legal email
- Number fields with numeric value etc.
<style>
* {
box-sizing: border-box;
}
.html-validation {
margin: auto;
width: 30%;
border: 1px solid green;
box-shadow: 5px 5px 8px green;
border-radius: 5px;
padding: 20px;
}
label {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
display: block;
text-align: center;
}
input {
width: 100%;
padding: 10px;
margin: 10px 0px;
border-radius: 10px;
}
input:invalid {
border: 1px solid red;
}
input:valid {
border: 1px solid green;
}
</style>
<form class="html-validation" action="#0" method="post">
<label for="firstName">First Name</label>
<input name="firstName" type="text" required>
<input type="submit">
</form>
Styles are applied as soon as the input becomes valid or invalid.
There are few other CSS selectors which does similar kind of work are:
:optional
- Selects all non-required elements in form and if we apply styles using this selector then applied to all optional elements in the form.
:required
- Opposite to optional and selects all required elements in the form.
:in-range
- selects elements with value specified is within the range - mostly applicable for input elements with max and min specified.
:out-of-range
- Opposite to in-range.
:readonly
- selects elements which are specified with readonly attribute
:read-write
- selects elements which are readable and writable. As such not mentioned as disabled and readonly.
:checked
- Selects all checked elements. Checkboxes and radio buttons, options.
:hover
- selects any element when user hovers over it
:visited
- applicable for links when user clicked and visited it.
:active
- selects when user selected it.
:disabled
- selects all elements with attribute mentioned as disabled
:focus
- Selects focused element
:empty
- selects elements with no children
Top comments (3)
Related, here is a list what you want to validate for name fields kalzumeus.com/2010/06/17/falsehood...
Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍
Very useful. Thanks a lot for sharing