Is there invalid state of Input range?

Viewed 1335

I need to define custom HTML5 form validation styles in my application's design system like Bootstrap. But I don’t know how to apply :invalid state to an <input type="range">.

console.log($('#test').val());
$('#test').val(50);
console.log($('#test').val());
.valid-message,
.invalid-message {
  display: none;
}

.input:valid ~ .valid-message {
  display: block;
  color: green;
}

.input:invalid ~ .invalid-message {
  display: block;
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="control">
  <input type="range" class="input range" id="test" min="1" max="20">
  <p class="valid-message">This is valid</p>
  <p class="invalid-message">This is invalid</p>
</div>

Is there invalid state of Input range? How can I reproduce that state?

4 Answers

But I did not know how to apply :invalid state to an <input type="range">.

Actually you can't apply :invalid state to an <input type="range">, because the value will always be set between the min and max values, and you can't force it to be out of range it will be automatically updated to fit the range.

If you check the MDN <input type="range"> specifications in the Value section, you can see that:

If an attempt is made to set the value lower than the minimum, it is set to the minimum. Similarly, an attempt to set the value higher than the maximum results in it being set to the maximum.

To have the range input in an invalid state just set the steps attribute. For <input type="range" min="0" max="10" step="0.1" /> a value of 0.25 is invalid. But according to MDN, most browsers might round the value to the nearest valid one.

Seems like Firefox doesn't do this, as my range input is highlighted in red when programatically setting some value that doesn't conform to (min + n * steps)

MDN - HTML attribute: step

Related