Skip to content

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

Open
thet wants to merge 15 commits into
masterfrom
validation-min-max
Open

thet wants to merge 15 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 added 11 commits November 26, 2026 02:27
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.
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.
@thet
thet force-pushed the validation-min-max branch from a3fe5a4 to 427c37b Compare November 26, 2026 02:01
thet added 3 commits November 26, 2026 03:22
…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.
…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.

Assisted-by: Claude Opus 5.5 <noreply@anthropic.com>
@thet
thet force-pushed the validation-min-max branch 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.

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