CSS Has Selector Form Validation
Style form fields based on validity with :has and :user-invalid for pure CSS feedback.
Code
input:invalid {
border-color: red;
}
input:user-invalid {
border-color: red;
background-color: #fee;
}
form:has(input:invalid) button[type="submit"] {
opacity: 0.5;
pointer-events: none;
}
label:has(+ input:invalid) {
color: red;
font-weight: bold;
}
.field:has(input:focus) {
outline: 2px solid blue;
}How the snippet works
:has() styles a parent by looking at its children, which lets markup validity be checked without script.
The rules target input:invalid, border-color: red; } input:user-invalid, color: red; font-weight: bold; } .field:has(input:focus) — each selector names the element it restyles, in source order.
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.CSS Specificity CalculatorCalculate CSS selector specificity scores using the standard (a, b, c) notation. Enter any selector and see its inline, ID, class, and element contributions instantly.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
FAQ
- Which elements does this stylesheet target?
- The rules bind to `input:invalid`, `border-color: red; } input:user-invalid`, `color: red; font-weight: bold; } .field:has(input:focus)`; when two rules tie in specificity, the one written later in the file wins.
Report a problem with this exampleOpens a pre-filled issue on GitHub.