Skip to content

feat(pat-validation): Support definition of minimum or maximum number of selections. - #1249

Merged
thet merged 27 commits into
masterfrom
validation-min-max
Nov 28, 2026
Merged

thet merged 27 commits into
masterfrom
validation-min-max

Conversation

@thet

@thet thet commented May 9, 2025 •

Copy link
Copy Markdown
Member

Hi @cornae

we had the need to validate if at least one checkbox in a group of checkboxes was checked.
This was not yet supported by pat-validation nor by the HTML specficiation.

As a side note - required radio buttons are supported. A required attribute on one or all radio inputs in a group of radio inputs is supported by the HTML specification and validated by pat-validation.

We were in need to quickly support that in one of our projects and I did a implementation which we deployed but still can change if there is anything to improve - behavior wise, parameter naming or whatever.

These parameters were added:

Property Description Default Type
message-min-values The error message when the minimim number of checked, selected or filled-out fields has not been reached. You need to select at least %{count} item(s). String
message-max-values The error message when the maximum number of checked, selected or filled-out fields has not been reached. You need to select at most %{count} item(s). String
min-values Minimum number of checked, selected or filled out form elements. null Integer (or null)
max-values Maximum number of checked, selected or filled out form elements. null Integer (or null)

Note: this does not only work with checkboxes but with any kind of input.
I recognized that we can use the same name for any kind of input - any input, select or textarea. All of the values will be submitted to the server. Therefore this implementation is not only limited to checkboxes but any kind of input.

Along the way I did some other improvements:

  • The documentation is updated and extended.

  • pat-validation now fully supports input elements outside the form itself, e.g.:

<input name="outside" form="myform" required>
<form id="myform">
</form>
<button form="myform">submit</button>
  • pat-validation also fully supports dynamic forms without re-initalizing or sending a special "pat-update" event. You can add form elements even without pat-inject and it should immediately take part in validation.

  • And a important one:
    For multiple input elements with the same name the error message was shown wether immediately after the last input which the user interacted with or the the end of a fieldset.checkbox element.
    I have changed that, so that the error message is just shown after the last input with the same name.
    We needed that also for our project and I believe it's better because it works just out of the box and there is no need to add a fieldset.checkbox element.

@thet
thet marked this pull request as draft May 9, 2025 14:18
@thet
thet force-pushed the validation-min-max branch 6 times, most recently from 86ee675 to 0e25a09 Compare May 13, 2025 22:01
@thet thet changed the title DRAFT: feat(pat-validation): Support definition of minimum or maximum number of selections. feat(pat-validation): Support definition of minimum or maximum number of selections. May 13, 2025
@thet
thet requested a review from cornae May 13, 2025 22:23
@thet
thet force-pushed the validation-min-max branch from 0e25a09 to 735ebda Compare May 13, 2025 22:26
@thet
thet marked this pull request as ready for review May 13, 2025 22:31
@thet
thet force-pushed the validation-min-max branch 2 times, most recently from 10c365d to cc1e043 Compare May 21, 2025 09:11
@thet
thet force-pushed the validation-min-max branch from cc1e043 to a3fe5a4 Compare June 17, 2025 20:54
@thet
thet force-pushed the validation-min-max branch 2 times, most recently from 427c37b to d6082e8 Compare November 26, 2026 02:23
@thet
thet requested a review from petschki November 26, 2026 11:13

@petschki petschki left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found two problems in the new group handling which I think should be fixed before a merge ... and point 3. which hits @plone/mockup directly.

All of this is from Jest tests on this branch, compared to the validation.js of master. I did not test in a browser.

1. Errors of single inputs get lost in a group

set_error and remove_error now work on all siblings of a group. When a valid input is checked, the state and the message of all other inputs of the group are removed.

Case master this branch
fieldset with min-values: 1, an empty required input and a checked checkbox in it, submit message at the input no message, submit prevented, button disabled
min-values: 1 on the form, an empty required input and a filled one message at the input no message
fieldset group, an input with an equality error input invalid, message input valid, no message

The user ends up with a disabled form and no hint. The documentation of this PR names min-values on the form as supported.

These three tests pass with the validation.js of master and fail on this branch:

    it("keeps the error of a required input in a wrapper group", async function () {
        document.body.innerHTML = `
          <form class="pat-validation">
            <fieldset data-pat-validation="min-values: 1">
              <input name="name" required>
              <label><input type="checkbox" name="agree" checked> Agree</label>
            </fieldset>
            <button>Submit</button>
          </form>
        `;
        const el = document.querySelector(".pat-validation");
        const instance = new Pattern(el);
        await events.await_pattern_init(instance);

        el.dispatchEvent(events.submit_event());
        await utils.timeout(1); // wait a tick for async to settle.

        expect(el.querySelector("[name=name]").validity.valid).toBe(false);
        expect(el.querySelectorAll("em.warning").length).toBe(1);
    });

    it("keeps the error of a required input with min-values on the form", async function () {
        document.body.innerHTML = `
          <form class="pat-validation" data-pat-validation="min-values: 1">
            <input name="name" required>
            <input name="city" value="Innsbruck">
            <button>Submit</button>
          </form>
        `;
        const el = document.querySelector(".pat-validation");
        const instance = new Pattern(el);
        await events.await_pattern_init(instance);

        el.dispatchEvent(events.submit_event());
        await utils.timeout(1); // wait a tick for async to settle.

        expect(el.querySelectorAll("em.warning").length).toBe(1);
    });

    it("keeps the equality error of an input in a wrapper group", async function () {
        document.body.innerHTML = `
          <form class="pat-validation">
            <input name="password" value="secret">
            <fieldset data-pat-validation="min-values: 1">
              <input name="confirm" value="other"
                     data-pat-validation="equality: password">
              <input name="hint" value="a hint">
            </fieldset>
            <button>Submit</button>
          </form>
        `;
        const el = document.querySelector(".pat-validation");
        const instance = new Pattern(el);
        await events.await_pattern_init(instance);

        el.dispatchEvent(events.submit_event());
        await utils.timeout(1); // wait a tick for async to settle.

        expect(el.querySelector("[name=confirm]").validity.valid).toBe(false);
        expect(el.querySelectorAll("em.warning").length).toBe(1);
    });

2. The run time explodes for groups

siblings() is called nested in set_error and remove_error, and inputs is computed again on each access. Time for one check of all inputs in jsdom, three runs each, all inputs valid:

Form Inputs master (ms) this branch (ms)
no group 50 33, 25, 25 29, 21, 18
no group 100 95, 85, 88 94, 90, 87
no group 200 330, 316, 353 597, 571, 583
min-values on the form 50 21, 21, 20 209, 206, 218
min-values on the form 100 77, 76, 77 2097, 2080, 2099
min-values on the form 200 310, 329, 323 29140, 29985, 29351

With a group on the form the time grows 10 to 14 times when the number of inputs doubles; on master it grows about 4 times. Without a group this branch is as fast as master up to 100 inputs and about 1.8 times slower at 200.

I measured await instance.validate_all(event) on this branch and the same loop over instance.inputs with check_input on master. Browsers are faster than jsdom, so the absolute times are smaller there.

I think 1 and 2 have the same root: the shared state should only hold the error of the group (min-values, max-values), not the own errors of its inputs. That would also remove the nested siblings() calls.

3. A synthetic blur does not trigger the validation any more

The pattern now listens to focusout on the document, not to blur on the input, and the patterns in this repository are changed with it. Mockup's pat-select2 dispatches events.blur_event() on select2-blur. With this PR a required select2 field which is left empty is only checked on submit.

Either pat-validation also listens to blur in the capture phase, or Mockup has to follow with the Patternslib update. For other add-ons it is a silent change which should be in the release notes.

Smaller points

  • Hidden inputs are counted. With <input type="hidden" name="x" value="0"> and checkboxes named x, min-values: 1 is always met; the submit goes through with no checkbox checked. From the code, <input type="submit" name="…"> and disabled inputs are counted in a wrapper group too. I did not test that.
  • Inputs with the same name and an own error. With two inputs of the same name and equality, the first loses its error state when the second is checked. The message was already missing on master, but the state stayed there.
  • Position of the message. It is now after the last input of the group, not after the first. With Bootstrap markup like in Plone (input and label as siblings in .form-check) it still ends up between input and label; that was already so on master.
  • Listening on pat-update is gone. The jQuery event to initialize the inputs again is no longer handled. With the delegation that makes sense, but it is a change for the release notes too.
  • Listeners on the document. Each instance registers three listeners on document. They are removed in destroy(), but nothing in the core calls it when a form is removed, e.g. after an injection or when a modal is closed. After five replaced forms there are 15 listeners. They return after one comparison, so the cost is small, but they are called for every input, change and focusout in the document from then on. On master the listeners stayed on the removed inputs and were never called again. Memory is not the problem here: event_listener_map already keeps the removed elements on master.
  • destroy() is not complete. It removes the listeners on the document, but not the submit listener and not novalidate. After destroy() a submit is still validated and prevented.

thet added 10 commits November 27, 2026 15:53
Note the slight behavior changes:
- On submit, inputs are now checked with `stop: true`. Dependent inputs
  (not-after/not-before) do not need to be re-checked separately as all
  inputs are checked anyway.
- When an element was disabled due to an error, the whole form is
  re-checked including the input which triggered the check.
… of selections.

Assisted-by: Claude Opus 5.5
…of inputs with the same name.

Assisted-by: Claude Opus 5.5
thet added 17 commits November 27, 2026 15:56
Introduce event delegation and register input, change and focusout event
handlers on the document level.

This reduces the amount of registered event handlers which potentially
improves performance and also supports dynamic forms where form elements
can be added at any time.

The event listeners on the document are removed when the pattern is
destroyed.

As blur events do not bubble, pat-auto-suggest, pat-date-picker and
pat-datetime-picker now dispatch a focusout event instead of a blur event
to trigger the validation.

Ref: ADR 0005
Assisted-by: Claude Opus 5.5
Use a WeakMap for the per-input debouncers, so that inputs which were
removed from a dynamic form are not kept alive by the pattern instance.

Assisted-by: Claude Opus 5.5
…ation constraints.

Run the custom validation checks one after another and only continue
with the next check if no error was set by a previous one. Remove the
error message only after all checks were done and the input is valid.

Assisted-by: Claude Opus 5.5
…pat-validation.

Assisted-by: Claude Opus 5.5
…ements for groups of inputs.

When `min-values` or `max-values` is defined on a wrapper element, like a
fieldset, all inputs within that wrapper form a group, regardless of
their names. Counting, the shared validation state and the error message
placement then apply to the whole group.

When the options are defined on the input itself, the group is still
defined by the inputs with the same name.

Ref: ADR 0006
Assisted-by: Claude Opus 5.5
…-values.

This reverts commits 27843a9 and f722cec (ADR 0006).

All members of a wrapper group shared one validation state. A valid
input cleared the errors of all other inputs of the group, e.g. of a
required input or of an input with an equality constraint in the same
fieldset - or in the whole form, if min-values was defined there. The
form was then disabled without an error message. In addition, the group
was computed in nested loops, which made the validation of large groups
very slow.

min-values and max-values are again applied to the inputs with the same
name. Add regression tests for the lost errors.

Assisted-by: Claude Opus 5.5
Get the inputs with the same name via the form's named lookup instead of
filtering all form elements with a CSS selector. When removing an error,
clear the state of the siblings directly instead of looking up the
siblings of each sibling again.

Checking all inputs of a form with 200 text inputs in jsdom now takes
about 230ms instead of 970ms before and 370ms on master.

Assisted-by: Claude Opus 5.5
…buttons for min-values and max-values.

A hidden input with the same name as a group of checkboxes is a common
way to submit a default value if no checkbox is checked. It was counted
as a value, so `min-values: 1` was always met.

Assisted-by: Claude Opus 5.5
@thet
thet force-pushed the validation-min-max branch from d6082e8 to 2dd12e2 Compare November 28, 2026 02:13
@thet

thet commented Nov 28, 2026

Copy link
Copy Markdown
Member Author

AI Response:

Thanks for the thorough review and the benchmarks!

1. Errors of single inputs get lost in a group / 2. The run time explodes for groups

You're right. Both come from the shared validation state of the wrapper groups. I removed the wrapper groups from this PR (8396103). min-values and max-values apply to the inputs with the same name again. Your three tests are added as regression tests and pass.

I also sped up the lookup of inputs with the same name (2f22fe4). It now uses form.elements.namedItem() instead of filtering all form elements with a CSS selector, and remove_error no longer computes the siblings of each sibling. With your setup in jsdom, checking all 200 inputs now takes about 230 ms, both with and without min-values on the form, compared to about 370 ms on master.

The wrapper groups are parked on a separate branch, validation-min-max-wrapper-groups. There, each input keeps its own error and its group errors separately, and its validity is setCustomValidity(own || group), so the state stays on the individual inputs. ADR 0006 on that branch describes it. We can revisit it when groups of differently named inputs are needed.

3. A synthetic blur does not trigger the validation any more

Mockup follows with a change in pat-select2: it dispatches a bubbling focusout in addition to blur, so it works with both the old and the new pat-validation. The removal of the blur listener and of the pat-update handling will go into the release notes.

Smaller points

  • Hidden inputs are counted: fixed (d9e9cdc). Hidden inputs, disabled inputs and buttons are no longer counted for min-values and max-values.
  • Inputs with the same name and an own error: unchanged in this PR. Inputs with the same name still share their state. On the parked branch the own errors are kept separately.
  • Position of the message: placing it after the last input with the same name is intended (90df036). The Bootstrap case was the same on master.
  • Listeners on the document / destroy(): the branch is now rebased on master, which destroys patterns automatically when they are removed from the DOM (Lifecycle auto destroy #1309). This removes the document listeners and the submit listener. novalidate is deliberately not removed; undoing DOM changes in destroy() is out of scope for now.

@thet

thet commented Nov 28, 2026 •

Copy link
Copy Markdown
Member Author

Human response:

There is a breaking change - the change from blur to focusout. We could also handle that backwards-compatible and stay with the non-bubbling blur event and use a capture-event-listener. But that gets the code messier, I think. Currently I'm -1, especially as I think the risk is mitigated - only Mockup from all the packages I have has 1 occurrence of evoking a blur event to make Select2 compatible with standard JavaScript events - so a hack already.
There is a PR for the Mockup fix: plone/mockup#1697

Second thing: There is already some grouping support! The checkboxes can be counted, and actually any input can be included in a group of inputs with the same name. The mentioned feature of input-groups was structural, via HTML element containment.
This is not easily achievable, so we better leave that out.

@thet
thet merged commit 2186cfc into master Nov 28, 2026
1 check passed
@thet
thet deleted the validation-min-max branch November 28, 2026 02:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants