If you have a field at the same time required
and an empty field, it is in fact an invalid field - after all, a required field, to be valid needs to have data :)
What you can do in this case, to improve the initial user experience, is to "delay" the CSS to appear only after there is interaction with the form.
In this intention, two intermediate solutions follow. One is based on the autofocus
, and it’s pure CSS. The other has some similarity to the @Sergio response, but with a view to cases where there is the send button (or other equivalent procedure).
For one field only: CSS
If you have a unique field, can solve without JS:
input { border: 2px solid #ccc; padding: 8px; }
input:invalid { border-color: red; }
input:valid,
input:focus:valid { border-color:green; }
input:focus { border-color: #ccc; !important; }
<input required type="text" pattern="\d*" placeholder="Somente Digitos" min="1" autofocus />
For several fields: JS
The following JS function causes, in addition to the field to respond visually to the requirements in the loss of focus, in an eventual attempt to send the fields all receive the CSS indicating their status.
In this way, the feedback happens in the form even without a certain field being visited.
var hi = document.querySelectorAll('input.off');
for (var i = 0; i < hi.length; i++) hi[i].onblur = function(){ this.classList.add('hl'); }
function highlightAll() { for (var i = 0; i < hi.length; i++) hi[i].classList.add('hl'); }
input { border: 2px solid #ccc; padding: 8px; }
input.hl:invalid { border-color: red; }
input.hl:valid { border-color:green; }
<input class="off" type="text" required pattern="\d*" placeholder="Somente Digitos" min="1" /><br>
<input class="off" type="text" required placeholder="Qualquer coisa" /><br>
<input class="off" type="text" placeholder="Campo não obrigatório" /><br>
<button onClick="highlightAll()">enviar</button>
It turns out that if the field has an initial value o
placeholder
will not appear. Can you start input with a "neutral" state? Orvalid
, norinvalid
?– Renan Gomes
@rnxn as I wrote in the answer has to give some value, zero for example, or use Javascript. There is no way to "shut down" in CSS.
– Sergio