I need to know how to make an empty-non-required input
element invalid.
For example:
<input pattern="[0-9]+" title="" />
This field is :valid by default, as is not required. I need to turn it :invalid if it is empty.
Thank you all in advance. Cheers.
EDIT:
HTML:
<div>
<input type="text" name="Country" pattern="[a-zA-Z ]+" title="" placeholder="Country" />
<a href="#">Toggle</a>
</div>
CSS:
input:valid + a
{
color: blue;
}
The <a>
starts blue since there is no text inside the <input>
which is not required.
The pseudo-class :valid state for an empty-non-required <input>
element is true.
I need the <a>
to remain uncolored when the <input>
field is empty.
This answer addresses the clarified/modified question, which seems to be about styling. An input
element cannot match the selector :invalid
if its value is empty, since such an element is exempted from constraint validation (as explained in my first answer). There is no selector for checking that the value of an input
element is empty or non-empty. (The :empty
pseudo-class tests for the content being empty, and an input
element always has empty content.)
So this cannot be done in CSS (alone). You can use JavaScript e.g. so that any input operation causes the input
element value to be checked. If the value is nonempty, put the input
element to a class, say ok
. Modify the CSS selector accordingly.
<style>
input:valid + a.ok {
color: blue;
}
</style>
<input ... oninput=check(this)>
...
<script>
function check(el) {
el.nextElementSibling.className = el.value ? 'ok' : '';
}
This works in sufficiently modern browsers. If wider browser coverage is needed, you may need to add event attributes like onkeypress
and onpaste
etc. that are used to run the same check. (And nextElementSibling
might need to be replaced by some clumsier way of getting at the next element.)
Update, as per the comment below, you can simplify the code somewhat by setting the class on the input
element rather than the a
element. This means that the CSS selector would be input:valid.ok + a
and the JavaScript assignment statement would have just el.className
as the left-hand side. Regarding browser coverage, it’s probably not an issue here as compared with the basic restriction caused by the use of the :valid
pseudo-class, which isn’t supported by IE 9 and earlier.