{"id":335874,"date":"2021-03-08T08:03:44","date_gmt":"2021-03-08T16:03:44","guid":{"rendered":"https:\/\/css-tricks.com\/?page_id=335874"},"modified":"2021-03-08T08:04:34","modified_gmt":"2021-03-08T16:04:34","slug":"form-validation-styling-on-input-focus","status":"publish","type":"page","link":"https:\/\/css-tricks.com\/snippets\/css\/form-validation-styling-on-input-focus\/","title":{"rendered":"Form Validation Styling on Input Focus"},"content":{"rendered":"\n
\/* Only show invalid ring while not focused *\/\ninput:not(:focus):not(:placeholder-shown):invalid {\n border-color: var(--color-invalid);\n}\ninput:not(:focus):not(:placeholder-shown):invalid ~ .error-message {\n display: block;\t\n}\n\n\/* Only show valid ring while not focused and if a value is entered *\/\n\/* :empty won't work here as that targets elements that have no childeren. Therefore we abuse :placeholder-shown *\/\ninput:not(:focus):not(:placeholder-shown):valid {\n border-color: var(--color-valid);\n}<\/code><\/pre>\n\n\n\nPulling this straight from the Weekly Platform News, where \u0160ime Vidas covers two long ongoing issues<\/a> with using :invalid<\/code> to style form input validation. Apparently, what happens is…<\/p>\n\n\n\n- [inputs] become
:invalid<\/code> while the user is still typing the value.<\/li>- If a form field is required (
<\/code>), it will become :invalid<\/code> immediately on page load.<\/li><\/ul>Both of these behaviors are potentially confusing (and annoying<\/a>), so websites cannot rely solely on the :invalid<\/code> selector to indicate that a value entered by the user is not valid. However, there is the option to combine<\/a> :invalid<\/code> with :not(:focus)<\/code> and even :not(:placeholder-shown)<\/code> to ensure that the page\u2019s \u201cinvalid\u201d styles do not apply to the \uff1cinput\uff1e<\/code> until the user has finished entering the value and moved focus to another element.<\/p><\/blockquote>\n\n\n\nRyan Florence sums this up nicely in a tweet:<\/p>\n\n\n\n
I prefer when forms wait for blur before freaking out 🤨 pic.twitter.com\/aLKVovpCao<\/a><\/p>\u2014 Ryan Florence (@ryanflorence) January 27, 2021<\/a><\/blockquote>