Is the input field valid while empty?

I experimented with css pseudo-classes and pseudo-elements, and I found that I was not able to get around.

Consider the following html input field:

<input type="number" value="1" min="1" max="1000" step="1" pattern="\d" /><span></span> 

To reach three states: empty, valid and invalid. I use :: after the pseudo-element (applies to the range adjacent to the input) to add a check mark when the value of the filed is valid, and X when the value is invalid.

I use the pseudo classes: valid and: invalid, and it seems that when the input field is empty (value = ""), its state is also valid.

The following is a description of the CSS:

 .v3_forms input[value=""] + span::after { content: ""; } .v3_forms input:valid + span::after { content: "\2713"; color: limegreen; } .v3_forms input:invalid + span::after { content: "X"; color: #ce0000; } 

For what I can say, after clearing the value in the browser, the second css rules take precedence, although the specifics are the same.
I tested selectors here: a specificity calculator , and it seems like attributes and pseudo-classes have the same weight.

+5
source share
1 answer

An empty string by default has a valid value:

User agents must allow the user to set the value to an empty string *.

If you want to require a value for a field, you need to add the required attribute:

 .v3_forms input[value=""] + span::after { content: ""; } .v3_forms input:valid + span::after { content: "\2713"; color: limegreen; } .v3_forms input:invalid + span::after { content: "X"; color: #ce0000; } 
 <div class="v3_forms"> <input type="number" value="1" min="1" max="1000" step="1" pattern="\d" required /><span></span> </div> 

This applies to a specific example in your question, but the same is true for any of the <input /> elements that accept user input.

* See whatwg link.

+6
source

All Articles