The out-of-range selector (for styling when a value is not correct)
Have you always wanted to dynamically validate the values entered by your users in a form field without using JavaScript? Here's how to change the style of a field when a number entered by the user is invalid!
Step 1: HTML
Let's start by creating a very classic form field, which has a number
type:
<input type="number" min="0" max="100" placeholder="Discount Percentage" />
We will use the example of a user who must enter a discount percentage for a product. We do not accept negative percentages (that would be very strange, wouldn't it?) and percentages above 100: after all, we are not going to give money to our buyers when they purchase a product.
Step 2: CSS
Let's start by styling our form field very simply:
input {
width: 300px;
padding: 15px;
border-radius: 5px;
border: 3px solid silver;
outline: none;
}
Nothing new and everything is rather simple to understand: our input will be 300px
wide with a 3px
wide border.
Step 3: Detecting an Incorrect Value
We just need to use out-of-range
to apply the style to the input
element:
input:out-of-range {
border-color: red;
background: #ff758f;
}
And that's it! Try entering a value that is not valid.
Step 4: Optimization
The problem is that currently all our inputs receive this selector, and that's not very efficient... We can use out-of-range
on fields that contain a minimum and a maximum number.
It's therefore very easy to specify that out-of-range
should only be used on inputs with a type
attribute that equals number
.
input[type="number"]:out-of-range {
border-color: red;
background: #ff758f;
}
We now have very simple and well-thought-out code that works wonderfully well to change the style of our fields when a value is not correct.