Skip to content

[selectors] pseudo selector to match forms ValidityState #1525

Open

Description

@jimmywarting

The Problem

When I did put a pattern to one of my form elment, it yields a tooltip saying "Enter a correct pattern"
The browser don't do a good job at displaying the correct pattern to use. So i need a way to inform them how the field should be written (look like)

<input 
  type="text"
  name="username"
  minlength="2"
  maxlength="20"
  required
  pattern="^[a-zA-Z][a-zA-Z0-9-_\.]{1,20}$"
/>

The solution

I would want it to behave a little like angular´s ngMessage, see demo

Say you got custom errors like this:

<input ...>
<div class="required">Username is required</div>
<div class="minlength">Username is too short</div>
<div class="maxlength">Username is too long</div>
<div class="pattern">Use only letters and numbers</div>

Now to style the right error message green or red, show or hide. I would want to use the same properties that exist on the constraints object input.validity (ValidityState)

ValidityState {
  badInput, patternMismatch, rangeOverflow, rangeUnderflow
  stepMismatch, tooLong, tooShort, typeMismatch, valueMissing
}
input:valueMissing ~ .required {display: block}
input:tooShort ~ .minlength {display: block}
input:tooLong ~ .maxlength {display: block}
input:patternMismatch ~ .pattern {display: block}

Activity

  1. SebastianZ commented on Jun 16, 2017

    @SebastianZ
    Contributor

    This is covered by the :invalid pseudo-class.

    Sebastian

  2. jimmywarting commented on Jun 16, 2017

    @jimmywarting
    Author

    the :invalid is too general.

  3. SebastianZ commented on Jun 16, 2017

    @SebastianZ
    Contributor

    I see. And you're right, there doesn't seem to be more fine-grained matching of invalidity except the :out-of-range pseudo-class.

    Note that CSS uses hyphen-separated syntax, not camel case. So, your proposal should rather look like this:

    input:value-missing ~ .required { display: block; }
    input:too-short ~ .minlength { display: block; }
    input:too-long ~ .maxlength { display: block; }
    input:pattern-mismatch ~ .pattern { display: block; }

    Another way would be to allow parameters for the :invalid pseudo-class. That would group the different error types. I.e. this could then look like:

    input:invalid(value-missing) ~ .required { display: block; }
    input:invalid(too-short) ~ .minlength { display: block; }
    input:invalid(too-long) ~ .maxlength { display: block; }
    input:invalid(pattern-mismatch) ~ .pattern { display: block; }
    input:invalid(out-of-range) ~ .outofrange { display: block; }

    which would allow to match different types of errors by allowing to provide multiple keywords:

    input:invalid(too-short, too-long) ~ .invalidlength { display: block; }

    Furthermore, for empty inputs there is already issue #1283. So empty inputs requiring a value could then also be matched via input:required:empty. Though an explicit way to check whether a required field is missing the value is probably nicer and more consistent to the other proposed pseudo-classes.

    Sebastian

  4. jimmywarting commented on Jun 16, 2017

    @jimmywarting
    Author

    Like the idea! Which we had came up with parameters for the :invalid pseudo-class before we introduced :out-of-range, maybe that would not have existed if we came up with this before.

    It seems like this idea of parameters is also better feature wise if we decide to add new validity properties in the feature...

  5. jimmywarting commented on Jun 16, 2017

    @jimmywarting
    Author

    Just for the shake of it i wrote a jQuery.expr

    $.extend($.expr[':'], {
      validity: (node, i, args) => 
        args[3]
        .replace(/-([a-z])/g, g => g[1].toUpperCase())
        .split(',')
        .some(prop => node.validity[prop.trim()])
    })
    $('input:validity(value-missing)').css('color', 'red')
  6. added and removed
    selectors-4
    on Jan 1, 2018
  7. lukewarlow commented on Feb 16, 2025

    @lukewarlow
    Member

    I think the above proposals of either making invalid functional (along with user-invalid) or adding new pseudo classes is a good idea and is a step towards improving styling of form control errors based on validation state.

    :value-missing is probably covered by the existing proposed :blank psuedo combined with :required but could be nice to include for completeness. Instead of invalid(out-of-range) we could potentially do below-range and above-range to offer even more granularity?

  8. alexnozer commented on Mar 27, 2025

    @alexnozer

    I find this suggestion useful. Currently, we have the :valid/:invalid and :user-valid/:user-invalid selectors. However, they are too generic and only indicate whether the value is valid or invalid, without providing further details. There are also :in-range/:out-of-range selectors, which specify whether the value falls within the defined range. However, there are no corresponding selectors for the pattern, minlength/maxlength, type and other attributes. It would be useful to introduce new selectors for a one-to-one correspondence with the ValidityState properties.

    A set of selectors might look as follows (presented in the table):

    HTML attribute ValididtyState CSS invalid selector CSS valid selector
    required valueMissing :value-missing :value-exists
    min rangeUnderflow :range-underflow and also match current :out-of-range :in-range
    max rangeOverflow :range-overflow and also match current :out-of-range :in-range
    minlength tooShort :too-short :optimal-length
    maxlength tooLong :too-long :optimal-length
    type typeMismatch :type-mismatch :type-match
    step stepMismatch :step-mismatch :step-match
    pattern patternMismatch :pattern-mismatch :pattern-match

    A combination of the :not() pseudo-class and CSS invalid selectors can be used as an alternative to CSS valid selectors (e.g., :not(:pattern-mismatch) instead of :pattern-match).

    A set of these selectors would enable the addition of hidden error messages that can be displayed without the need for JavaScript. This approach can be useful for basic form validation and progressive enhancement.

  9. Crissov commented on Mar 27, 2025

    @Crissov
    Contributor

    The special cases of :out-of-range should probably have similar names, e.g. :below-range and :above-range, or they should be aligned with the proposed string classes, i.e. :too-low/:too-small and :too-high/:too-large, or those should be aligned, e.g. :below-length and :above-length.

  10. SebastianZ commented on Oct 8, 2025

    @SebastianZ
    Contributor

    Given that all commenters are positive about this, I add this to the agenda.
    And I go ahead and propose a resolution:

    Add :invalid() and :user-invalid() functional pseudo-classes (complementing the existing non-functional pseudo-classes) taking one of the keywords matching the states defined for ValidityState.

    Iterating on the previous suggestions and the table provided by @alexnozer, here's a complete table of the suggested keywords for the pseudo-classes:

    HTML attribute ValidityState keyword for invalid state
    - badInput bad-input
    - customError custom-error
    pattern patternMismatch pattern-mismatch
    min rangeUnderflow range-underflow and out-of-range
    max rangeOverflow range-overflow and out-of-range
    step stepMismatch step-mismatch
    maxlength tooLong too-long
    minlength tooShort too-short
    type typeMismatch type-mismatch
    required valueMissing value-missing

    Note: In some cases multiple states may match, e.g. when there's a pattern mismatch and the string is too short. That would be covered by chaining the pseudo-classes, i.e. :invalid(pattern-mismatch):invalid(too-short).


    I am not convinced yet that we also need to distinguish between different valid states. E.g. what's the reason for matching :user-valid(optimal-length) when there's a pattern mismatch?

    Anyway, if there are strong reasons to add them, as well, here's the table listing them:

    HTML attribute ValidityState keyword for valid state
    - badInput accepted-input
    - customError -
    pattern patternMismatch pattern-match
    min / max rangeUnderflow / rangeOverflow in-range
    step stepMismatch step-match
    maxlength / minlength tooLong / tooShort optimal-length
    type typeMismatch type-match
    required valueMissing value-exists

    Sebastian

  11. 6 remaining items

  12. AutoSponge commented on Mar 18, 2026

    @AutoSponge

    Assuming following best-practice and associating the message with the input for AT (aria-describedby), how does this ensure multiple messages aren't sent to the axTree?

  13. SebastianZ commented on Mar 18, 2026

    @SebastianZ
    Contributor

    Assuming following best-practice and associating the message with the input for AT (aria-describedby), how does this ensure multiple messages aren't sent to the axTree?

    The pseudo-classes don't have any effect on the accessibility tree. They are only used to match form fields that are in a specific invalid state.

    Sebastian

  14. AutoSponge commented on Mar 19, 2026

    @AutoSponge

    The pseudo-classes don't have any effect on the accessibility tree. They are only used to match form fields that are in a specific invalid state.

    I didn't explain it well. It needs to have an effect or it won't work. Best practice is to currently render an input with the error message related by aria-describedby. This does not change that. And when someone tries to use it, it will have a worse outcome. Placing several errors together, rendered but hidden, will all read out. JS is still needed to do the connections dynamically for AT.

      <label for="password">
        Password
        <span class="required" aria-hidden="true">*</span>
        <span class="sr-only">required</span>
      </label>
      <input
        type="password"
        id="password"
        name="password"
        autocomplete="new-password"
        aria-describedby="err"
      >
      <p id="err">Your password needs to have at least eight characters.</p>
  15. Crissov commented on Mar 19, 2026

    @Crissov
    Contributor

    I understand that some authors would like keywords match those used in ValidityState by HTML DOM, just adjusted to kebab-case. They have been chosen rather inconsistently, though. External compatibility is a sound goal, but I still believe that these should follow a common pattern in Selectors/CSS, e.g.:

    Resolution Variant 1: “mismatch” suffix Variant 2: qualifier prefix Variant 3: single word
    bad-input value-mismatch bad-value/-input ✅ bad, null, misentry, illformed
    custom-error custom-error ✅ custom-requirement custom
    pattern-mismatch pattern-mismatch ✅ failed-pattern/-match malformed, mismatch(ed)
    range-underflow range-underflow ✅ under-/below-range (too-)small
    range-overflow range-overflow ✅ over-/above-range (too-)large
    out-of-range range-mismatch off-/outside-range (✅) divergent, deviant, outlier
    step-mismatch step-mismatch ✅ wrong-step misaligned, maladjusted, irregular
    too-long length-overflow over-/above-length (too-)long ✅
    too-short length-underflow under-/below-length (too-)short ✅
    — length-mismatch wrong-/off-length misfit
    type-mismatch type-mismatch ✅ wrong-type incompatible
    value-missing value-/value-missing ✅ void-value required
  16. lukewarlow commented on Mar 19, 2026

    @lukewarlow
    Member

    We can definitely open a bikeshedding issue for the specific tokens

  17. SebastianZ commented on Mar 20, 2026

    @SebastianZ
    Contributor

    @AutoSponge:

    The pseudo-classes don't have any effect on the accessibility tree. They are only used to match form fields that are in a specific invalid state.

    I didn't explain it well. It needs to have an effect or it won't work. Best practice is to currently render an input with the error message related by aria-describedby. This does not change that. And when someone tries to use it, it will have a worse outcome. Placing several errors together, rendered but hidden, will all read out. JS is still needed to do the connections dynamically for AT.

    So if I understand you correctly, you mean the given use case of exposing the correct error message related to a specific validity state should have an effect on the AT, correct?

    Then I'd argue that this should rather be an ARIA feature, meaning it should be possible to associate an error message with the right validity state directly within HTML. How exactly that's achieved needs to be discussed. Mind filing an issue in the ARIA repo to discuss that? Related resources seem to be https://www.w3.org/WAI/ARIA/track/issues/651 and w3c/aria#2048.
    Though I still believe it's valuable to also expose the validity state to CSS via the resolved on pseudo-class extensions, as they allow authors to style things differently based on that state and they are not restricted to the given use case. Both features should go hand in hand, though.

    Sebastian

  18. AutoSponge commented on Mar 24, 2026

    @AutoSponge

    Currently, you need JS and ARIA to associate an input and error message using well-supported features:

    • aria-describedby connects 1+ container statically and JS writes the message(s) into the DOM dynamically.
    • aria-describedby 1+ static, pre-filled error containers get dynamically associated by JS updating the attr value.

    The axTree picks up any linked description content even when hidden, so association or message must be dynamic (JS) to be accurate. For this to work with the proposal, JS would need to update the message association. No ARIA proposal needed. This is not a pure CSS solution to inline validation.

    <label for=input1>Label</label>
    <input id=input1 aria-describedby="{applied by JS}">
    <p id=msg1>message 1</p> <!-- visible when CSS matches error condition -->
    <p id=msg2>message 2</p>

    Then there's a less-well-supported technique (looking at you Safari on MacOS):

    • aria-errormessage statically associates the container(s) and JS applies aria-invalid and writes the correct message dynamically.
    • aria-errormessage dynamically associates the correct message and aria-invalid is applied dynamically.

    The message can be hidden by CSS and it won't hit the axTree. However, only aria-invalid will trigger the axTree update. Since there's only one aria-invalid the association is all done in CSS.

    <label for=input1>Label</label>
    <input id=input1 aria-errormessage="msg1 msg2" aria-invalid="{toggled by JS}">
    <p id=msg1>message 1</p> <!-- visible when CSS matches error condition -->
    <p id=msg2>message 2</p>

    IMO, aria-errormessage works better with the proposal. But it's not widely supported. If we wanted a pure CSS solution, we'd need aria-errormessage to trigger updates to the axTree when the :invalid and like classes apply. But if ARIA wanted that, I'm sure they would have gone with :invalid from the start. I don't see an ARIA proposal here.

  19. Crissov commented on Mar 28, 2026

    @Crissov
    Contributor

    How is this not solvable by aria-linking a container of all possible error messages to the input element?

    <input aria-errormessage="errmsg">
    <aside id="errmsg">
      …
      <p class="length error message">Value too short or too long.</p>
      …
    </aside>
    .error.message {
      display: none;
    }
    [aria-errormessage="errmsg"]:invalid(too-short, too-long) ~ #errmsg > .length {
      display: revert;
    }

    For cases like this, it would be nice to have association selectors like :invalid(length) /aria-errormessage/ > .length, of course.

  20. AutoSponge commented on Mar 28, 2026

    @AutoSponge

    @Crissov AT will only convey the error message when aria-invalid=true. This is, I think, the best path forward but a) it's not a CSS-only solution and therefore needs a caveat/accessibility consideration warning that without JS it's not accessible and b) aria-errormessage is still not widely supported.

  21. added
    a11y-tracker
    on Apr 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs EditsNeeds Testcase (WPT)a11y-trackerselectors-5

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions