In HTML 5, we can mark inputs as required
and then select them with the [required]
pseudo-selector in CSS. But I only want to style them when they try to submit the form without filling out a required element. Is there a selector for this? How about for the little message box which pops up?
The :required selector selects form elements which are required. Form elements with a required attribute are defined as required. Note: The :required selector only applies to the form elements: input, select and textarea. Tip: Use the :optional selector to select form elements which are optional.
The :required CSS pseudo-class represents any <input> , <select> , or <textarea> element that has the required attribute set on it. This pseudo-class is useful for highlighting fields that must have valid data before a form can be submitted. Note: The :optional pseudo-class selects optional form fields.
The "standard" that has evolved is that required fields have an asterisk (*) next to them. Sometimes the asterisk is red to help it stand out a bit.
Indicating form controls as required using asterisks (*) Asterisk (*) next to a form control's label usually indicates it as "required". Oftentimes, this asterisk's purpose is then explained somewhere else on the page.
You can use :valid and :invalid selectors. Something like this
.field:valid { border-color:#0f0; } .field:invalid { border-color:#f00; }
However, this will only work in browsers that support native validation, and only for fields that make sense. As far as I know, right now that only means Chrome (maybe Safari, but haven't checked).
So by native validation I mean that in chrome if you do <input type="email">
the field's value will be validated for email type string (without any additional javascript), so the styles above will work. However, if you were to attach them to a type="text"
field, or a second password field (that is suppose to match the first), you'd only ever get green because everything is valid, and in the case of password, there's no "type" for that anyway.
Which basically means that to support all browsers, and more importantly, wider array of validations you still have to resort to javascript, in which case assigning .valid/.invalid class shouldn't be a problem. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With