20 July 2015

:invalid pseudo class works on form elements too!

Discovered this by accident and there seems to be very little coverage in the blogosphere so I thought I'd share.

You're adding HTML5 validation on your input boxes now, right? And you're using styling to give the user helpful visual feedback, yeah? But did you know that when an input box inside a form is invalid, the parent form also has the :invalid pseudo class? This means we can now style any elements that are a sibling of the invalid input, amazing!

Here's an example where we make the submit button look disabled when an input field is invalid...

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        input{
            padding: 0.6em;
	}        
        input[type=submit]{
            cursor: pointer;
        }
        form:invalid input[type=submit]{
            cursor: default;
            opacity: 0.5;
        }
        input[type=text]{
            border: 1px solid #666;
        }
        input[type=text]:invalid{
            border-color: red;
        }
    </style>
</head>
<body>
    <form>
        <input type="text" name="username" pattern="[A-9a-z0-9 ]*" required>
        <input type="submit">
    </form>
</body>
</html>

The result is conventional and familiar visual feedback that suggests the form is being disabled/enabled....

FormInvalidBig

Obviously the button is not actually having it's disabled attribute changed, for that you would need some Javascript. But this is a pretty neat, low-level CSS option and remembering that the :invalid pseudo class operates at the parent form level might come in pretty handy.