From 432c417ebeba5758bea10c904366241ee8df29bc Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Thu, 26 Nov 2026 02:27:26 +0100 Subject: [PATCH 01/27] pat-validation: Autoformat. --- src/pat/validation/validation.js | 12 +++---- src/pat/validation/validation.test.js | 52 +++++++++++++-------------- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index 114161dd8..8cc7a4a4b 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -58,7 +58,7 @@ class Pattern extends BasePattern { // Make sure this event handler is run early, in the capturing // phase in order to be able to cancel later non-capturing submit // events. - { capture: true } + { capture: true }, ); this.initialize_inputs(); @@ -99,7 +99,7 @@ class Pattern extends BasePattern { // Registering again under the same name replaces the listener. for (const event_type of ["input", "change", "blur"]) { this.add_event_listener(input, event_type, event_type, (e) => - debouncer(e) + debouncer(e), ); } } @@ -199,7 +199,7 @@ class Pattern extends BasePattern { // with a single space. msg_attr = not_after_el?.labels?.[0]?.textContent.replace( /\s\s+/g, // replace all whitespace - " " // with a single space + " ", // with a single space ); msg_attr = msg_attr || not_after_el.name; } @@ -220,7 +220,7 @@ class Pattern extends BasePattern { // with a single space. msg_attr = not_before_el?.labels?.[0]?.textContent.replace( /\s\s+/g, // replace all whitespace - " " // with a single space + " ", // with a single space ); msg_attr = msg_attr || not_before_el.name; } @@ -397,11 +397,11 @@ class Pattern extends BasePattern { // executed within the web page context. const dompurify = (await import("dompurify")).default; const validation_message = dompurify.sanitize( - input.validationMessage || input[KEY_ERROR_MSG] + input.validationMessage || input[KEY_ERROR_MSG], ); const error_node = dom.create_from_string( - this.error_template(validation_message) + this.error_template(validation_message), ).firstChild; let fieldset; diff --git a/src/pat/validation/validation.test.js b/src/pat/validation/validation.test.js index ef249f0cd..f511a914d 100644 --- a/src/pat/validation/validation.test.js +++ b/src/pat/validation/validation.test.js @@ -206,7 +206,7 @@ describe("pat-validation", function () { await utils.timeout(1); // wait a tick for async to settle. expect(el.querySelectorAll("em.warning").length).toBe(1); expect(el.querySelectorAll("em.warning")[0].textContent).toBe( - "This value must be an integer." + "This value must be an integer.", ); expect(el.querySelector("#form-buttons-create").disabled).toBe(true); @@ -241,7 +241,7 @@ describe("pat-validation", function () { await utils.timeout(1); // wait a tick for async to settle. expect(el.querySelectorAll("div.validation-error").length).toBe(1); expect(el.querySelectorAll("div.validation-error")[0].textContent).toBe( - "need this" + "need this", ); }); @@ -637,7 +637,7 @@ describe("pat-validation", function () { expect(el.querySelectorAll("em.warning").length).toBe(1); expect(el.querySelector("em.warning").textContent).toBe( - "I'm sorry Dave, I can't let you do that." + "I'm sorry Dave, I can't let you do that.", ); }); @@ -684,7 +684,7 @@ describe("pat-validation", function () { expect(el.querySelectorAll("em.warning").length).toBe(1); expect(el.querySelector("em.warning").textContent).toBe( - "This value must be a valid email address." + "This value must be a valid email address.", ); inp.value = "person@mail.com"; @@ -722,7 +722,7 @@ describe("pat-validation", function () { expect(el.querySelectorAll("em.warning").length).toBe(1); expect(el.querySelector("em.warning").textContent).toBe( - "This value must be greater than or equal to 5" + "This value must be greater than or equal to 5", ); inp_min.value = 6; @@ -739,7 +739,7 @@ describe("pat-validation", function () { expect(el.querySelectorAll("em.warning").length).toBe(1); expect(el.querySelector("em.warning").textContent).toBe( - "This value must be less than or equal to 5" + "This value must be less than or equal to 5", ); inp_max.value = 5; @@ -862,7 +862,7 @@ describe("pat-validation", function () { expect(el.querySelectorAll("em.warning").length).toBe(1); expect(el.querySelectorAll("em.warning")[0].textContent).toBe( - "The value must be an integer." + "The value must be an integer.", ); inp.value = 5; @@ -892,7 +892,7 @@ describe("pat-validation", function () { expect(el.querySelectorAll("em.warning").length).toBe(1); expect(el.querySelectorAll("em.warning")[0].textContent).toBe( - "The value must be an integer." + "The value must be an integer.", ); inp.value = 5; @@ -1076,7 +1076,7 @@ describe("pat-validation", function () { await utils.timeout(1); // wait a tick for async to settle. expect(el.querySelectorAll("em.warning").length).toBe(1); expect(el.querySelectorAll("em.warning")[0].textContent).toBe( - "The date must be after 2011-11-11" + "The date must be after 2011-11-11", ); inp.value = "2023-02-23"; @@ -1084,7 +1084,7 @@ describe("pat-validation", function () { await utils.timeout(1); // wait a tick for async to settle. expect(el.querySelectorAll("em.warning").length).toBe(1); expect(el.querySelectorAll("em.warning")[0].textContent).toBe( - "The date must be before 2022-02-22" + "The date must be before 2022-02-22", ); inp.value = "2022-01-01"; @@ -1131,11 +1131,11 @@ describe("pat-validation", function () { expect(el.querySelectorAll("em.warning").length).toBe(2); expect(el.querySelectorAll("em.warning")[0].textContent).toBe( - "The date must be before woo date" + "The date must be before woo date", ); expect(el.querySelectorAll("em.warning")[1].textContent).toBe( - "The date must be after ye date" + "The date must be after ye date", ); }); @@ -1172,11 +1172,11 @@ describe("pat-validation", function () { expect(el.querySelectorAll("em.warning").length).toBe(2); expect(el.querySelectorAll("em.warning")[0].textContent).toBe( - "The date must be before date2" + "The date must be before date2", ); expect(el.querySelectorAll("em.warning")[1].textContent).toBe( - "The date must be after date1" + "The date must be after date1", ); }); @@ -1222,10 +1222,10 @@ describe("pat-validation", function () { await utils.timeout(1); // wait a tick for async to settle. expect(el.querySelectorAll("em.warning").length).toBe(2); expect(el.querySelectorAll("em.warning")[0].textContent).toBe( - "The start date must on or before the end date." + "The start date must on or before the end date.", ); expect(el.querySelectorAll("em.warning")[1].textContent).toBe( - "The end date must on or before the start date." + "The end date must on or before the start date.", ); // Fulfill the before/after constraint - same date @@ -1242,10 +1242,10 @@ describe("pat-validation", function () { await utils.timeout(1); // wait a tick for async to settle. expect(el.querySelectorAll("em.warning").length).toBe(2); expect(el.querySelectorAll("em.warning")[0].textContent).toBe( - "The start date must on or before the end date." + "The start date must on or before the end date.", ); expect(el.querySelectorAll("em.warning")[1].textContent).toBe( - "The end date must on or before the start date." + "The end date must on or before the start date.", ); // Fulfill the before/after constraint - start before end @@ -1316,7 +1316,7 @@ describe("pat-validation", function () { expect(el.querySelectorAll("em.warning").length).toBe(1); expect(el.querySelectorAll("em.warning")[0].textContent).toBe( - "This field is required" + "This field is required", ); }); @@ -1362,10 +1362,10 @@ describe("pat-validation", function () { await utils.timeout(1); // wait a tick for async to settle. expect(el.querySelectorAll("em.warning").length).toBe(2); expect(el.querySelectorAll("em.warning")[0].textContent).toBe( - "The start date/time must on or before the end date/time." + "The start date/time must on or before the end date/time.", ); expect(el.querySelectorAll("em.warning")[1].textContent).toBe( - "The end date/time must on or before the start date/time." + "The end date/time must on or before the start date/time.", ); // Fulfill the before/after constraint - same date @@ -1382,10 +1382,10 @@ describe("pat-validation", function () { await utils.timeout(1); // wait a tick for async to settle. expect(el.querySelectorAll("em.warning").length).toBe(2); expect(el.querySelectorAll("em.warning")[0].textContent).toBe( - "The start date/time must on or before the end date/time." + "The start date/time must on or before the end date/time.", ); expect(el.querySelectorAll("em.warning")[1].textContent).toBe( - "The end date/time must on or before the start date/time." + "The end date/time must on or before the start date/time.", ); // Fulfill the before/after constraint - start before end @@ -1454,7 +1454,7 @@ describe("pat-validation", function () { expect(el.querySelectorAll("em.warning").length).toBe(1); expect(el.querySelectorAll("em.warning")[0].textContent).toBe( - "This field is required" + "This field is required", ); inps[0].checked = true; @@ -1500,7 +1500,7 @@ describe("pat-validation", function () { await utils.timeout(1); // wait a tick for async to settle. expect(el.querySelectorAll("em.warning").length).toBe(1); expect(el.querySelectorAll("em.warning")[0].textContent).toBe( - "I would like this to be equal to password" + "I would like this to be equal to password", ); expect(el.querySelector("#form-buttons-create").disabled).toBe(true); @@ -1624,7 +1624,7 @@ describe("pat-validation", function () { // The text content should contain the message without HTML tags expect(warning_text).toContain( - "This field is required and must be filled out." + "This field is required and must be filled out.", ); // The innerHTML should contain the safe HTML (DOMPurify allows by default) From 0a6c36bdd28bff09f70ff4b7c0b2692fbc2bd78d Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Tue, 13 May 2025 22:06:10 +0200 Subject: [PATCH 02/27] maint(core dom): Add test to prove that jsDOM supports input elements outside forms. --- src/core/dom.test.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/core/dom.test.js b/src/core/dom.test.js index a9a3d26bb..af8d72caf 100644 --- a/src/core/dom.test.js +++ b/src/core/dom.test.js @@ -10,6 +10,24 @@ describe("core.dom tests", () => { jest.restoreAllMocks(); }); + describe("jsDOM tests", () => { + it("jsDOM supports input elements outside forms.", () => { + document.body.innerHTML = ` + +
+ +
+ `; + + const outside = document.querySelector("input[name=outside]"); + const inside = document.querySelector("input[name=inside]"); + const form = document.querySelector("form"); + + expect(outside.form).toBe(form); + expect(inside.form).toBe(form); + }); + }); + describe("document_ready", () => { it("calls the callback, once the document is ready.", async () => { let cnt = 0; From f3f782d2cfdbf115f51e8d4b021decab8dcdc3fc Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Tue, 13 May 2025 18:03:15 +0200 Subject: [PATCH 03/27] feat(core events): Add focusin and focusout event factories. --- src/core/events.js | 18 +++++++++++++++++- src/core/events.test.js | 18 ++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/core/events.js b/src/core/events.js index b0cf7677d..309d0b2eb 100644 --- a/src/core/events.js +++ b/src/core/events.js @@ -334,7 +334,7 @@ const await_pattern_init = (pattern) => { * A event factory for a bubbling and cancelable generic event. * * @param {string} name - The event name. - * @returns {Event} - Returns a blur event. + * @returns {Event} - Returns a DOM event. */ const generic_event = (name) => { return new Event(name, { @@ -393,6 +393,20 @@ const focus_event = () => { }); }; +const focusin_event = () => { + return new Event("focusin", { + bubbles: true, + cancelable: false, + }); +}; + +const focusout_event = () => { + return new Event("focusout", { + bubbles: true, + cancelable: false, + }); +}; + const input_event = () => { return new Event("input", { bubbles: true, @@ -456,6 +470,8 @@ export default { click_event: click_event, change_event: change_event, focus_event: focus_event, + focusin_event: focusin_event, + focusout_event: focusout_event, input_event: input_event, mousedown_event: mousedown_event, mouseup_event: mouseup_event, diff --git a/src/core/events.test.js b/src/core/events.test.js index 10d9a3300..2e61a0734 100644 --- a/src/core/events.test.js +++ b/src/core/events.test.js @@ -530,6 +530,24 @@ describe("core.events tests", () => { expect(catched).toBe("inner"); }); + it("focusin event", async () => { + outer.addEventListener("focusin", () => { + catched = "outer"; + }); + inner.dispatchEvent(events.focusin_event()); + await utils.timeout(1); + expect(catched).toBe("outer"); + }); + + it("focusout event", async () => { + outer.addEventListener("focusout", () => { + catched = "outer"; + }); + inner.dispatchEvent(events.focusout_event()); + await utils.timeout(1); + expect(catched).toBe("outer"); + }); + it("input event", async () => { outer.addEventListener("input", () => { catched = "outer"; From c8b3ed11a060d6e8e766aac1317c319c817b3519 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Tue, 13 May 2025 16:53:51 +0200 Subject: [PATCH 04/27] maint(pat-validation): Minor code cleanup. --- src/pat/validation/validation.js | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index 8cc7a4a4b..b85fdecb8 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -105,7 +105,11 @@ class Pattern extends BasePattern { } } - async check_input({ input, event, stop = false }) { + async check_input({ + input, // Input to check. + event = null, // Optional event which triggered the check. + stop = false // Stop flag to avoid infinite loops. Will not check dependent inputs. + }) { if (input.disabled) { // No need to check disabled inputs. return; @@ -428,11 +432,10 @@ class Pattern extends BasePattern { } } - // Do an initial check of the whole form when a form element (e.g. the - // submit button) was disabled. We want to show the user all possible - // errors at once and after the submit button is disabled there is no - // way to check the whole form at once. ... well we also do not want to - // check the whole form when one input was changed.... + // Check the whole form when a form element (e.g. the submit button) + // was disabled. We want to show the user all possible errors at once + // and after the submit button is disabled there is no way for the user + // to check the whole form at once. if (did_disable) { logger.debug("Checking whole form after element was disabled."); for (const _input of this.inputs.filter((it) => it !== input)) { From 27853c59ea660fa99fa34eb19f938e7b820bd0a7 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Tue, 13 May 2025 17:01:56 +0200 Subject: [PATCH 05/27] tech(pat-validation): Use this.form instead of this.el for clarity. --- src/pat/validation/validation.js | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index b85fdecb8..1193e50ed 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -42,8 +42,12 @@ class Pattern extends BasePattern { static order = 100; init() { + // The element is the form - make it clearer in the code what we're + // referring to. + this.form = this.el; + this.add_event_listener( - this.el, + this.form, "submit", "submit", async (e) => { @@ -62,19 +66,19 @@ class Pattern extends BasePattern { ); this.initialize_inputs(); - $(this.el).on("pat-update", () => { + $(this.form).on("pat-update", () => { this.initialize_inputs(); }); // Set ``novalidate`` attribute to disable the browser's validation // bubbles but not disable the validation API. - this.el.setAttribute("novalidate", ""); + this.form.setAttribute("novalidate", ""); } initialize_inputs() { const previous_inputs = this.inputs || []; this.inputs = [ - ...this.el.querySelectorAll("input[name], select[name], textarea[name]"), + ...this.form.querySelectorAll("input[name], select[name], textarea[name]"), ]; // Remove the listeners from inputs which are gone. @@ -86,7 +90,7 @@ class Pattern extends BasePattern { } } this.disabled_elements = [ - ...this.el.querySelectorAll(this.options.disableSelector), + ...this.form.querySelectorAll(this.options.disableSelector), ]; for (const input of this.inputs) { @@ -133,7 +137,7 @@ class Pattern extends BasePattern { if ( input_options.equality && - this.el.querySelector(`[name=${input_options.equality}]`)?.value !== + this.form.querySelector(`[name=${input_options.equality}]`)?.value !== input.value ) { const message = @@ -368,7 +372,7 @@ class Pattern extends BasePattern { } // disable selector - if (this.el.checkValidity()) { + if (this.form.checkValidity()) { for (const it of this.disabled_elements) { if (it.disabled) { it.removeAttribute("disabled"); From b3f09d626e94be6708213ba4279ee9120e832166 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Mon, 12 May 2025 11:12:41 +0200 Subject: [PATCH 06/27] tech(pat-validation): Create a validate_all API method. 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. --- src/pat/validation/validation.js | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index 1193e50ed..8c0556017 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -50,14 +50,11 @@ class Pattern extends BasePattern { this.form, "submit", "submit", - async (e) => { + async (event) => { // On submit, check all. // Immediate, non-debounced check with submit. Otherwise submit // is not cancelable. - for (const input of this.inputs) { - logger.debug("Checking input for submit", input, e); - await this.check_input({ input: input, event: e }); - } + await this.validate_all(event); }, // Make sure this event handler is run early, in the capturing // phase in order to be able to cancel later non-capturing submit @@ -75,6 +72,13 @@ class Pattern extends BasePattern { this.form.setAttribute("novalidate", ""); } + async validate_all(event) { + // Check all inputs. + for (const input of this.inputs) { + await this.check_input({ input: input, event: event, stop: true }); + } + } + initialize_inputs() { const previous_inputs = this.inputs || []; this.inputs = [ @@ -112,7 +116,7 @@ class Pattern extends BasePattern { async check_input({ input, // Input to check. event = null, // Optional event which triggered the check. - stop = false // Stop flag to avoid infinite loops. Will not check dependent inputs. + stop = false, // Stop flag to avoid infinite loops. Will not check dependent inputs. }) { if (input.disabled) { // No need to check disabled inputs. @@ -441,10 +445,7 @@ class Pattern extends BasePattern { // and after the submit button is disabled there is no way for the user // to check the whole form at once. if (did_disable) { - logger.debug("Checking whole form after element was disabled."); - for (const _input of this.inputs.filter((it) => it !== input)) { - await this.check_input({ input: _input, stop: true }); - } + await this.validate_all(); } } From 2feee462ebba6e2226a45cf19c8b7a5a0f588d00 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Mon, 12 May 2025 12:05:32 +0200 Subject: [PATCH 07/27] fix(pat-validation): When removing the error, also clear the error state of all siblings. --- src/pat/validation/validation.js | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index 8c0556017..e4ed2d83d 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -258,7 +258,7 @@ class Pattern extends BasePattern { if (!validity_state.customError) { // No error to handle. Return. - this.remove_error(input, true); + this.remove_error({ input }); return; } } else { @@ -361,8 +361,13 @@ class Pattern extends BasePattern { } } - remove_error(input, all_of_group = false, skip_event = false) { - // Remove error message and related referencesfrom input. + remove_error({ + input, + all_of_group = true, + clear_state = true, + skip_event = false, + }) { + // Remove error message and related references from input. let inputs = [input]; if (all_of_group) { @@ -370,6 +375,9 @@ class Pattern extends BasePattern { inputs = this.inputs.filter((it) => it.name === input.name); } for (const it of inputs) { + if (clear_state) { + this.set_error({ input: it, msg: "", skip_event: true }); + } const error_node = it[KEY_ERROR_EL]; it[KEY_ERROR_EL] = null; error_node?.remove(); @@ -392,7 +400,12 @@ class Pattern extends BasePattern { async set_error_message(input) { // First, remove the old error message. - this.remove_error(input, false, true); + this.remove_error({ + input, + all_of_group: false, + clear_state: false, + skip_event: true + }); // Do not set a error message for a input group like radio buttons or // checkboxes where one has already been set. From b3ec19f35f3b6f72e26536a54bec6eca9f681841 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Tue, 13 May 2025 17:16:01 +0200 Subject: [PATCH 08/27] feat(pat-validation): Support form elements outside the form. Assisted-by: Claude Opus 5.5 --- src/pat/validation/documentation.md | 16 ++++++++ src/pat/validation/validation.js | 47 ++++++++++++++-------- src/pat/validation/validation.test.js | 57 +++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 17 deletions(-) diff --git a/src/pat/validation/documentation.md b/src/pat/validation/documentation.md index a3dc74fdd..62731c091 100644 --- a/src/pat/validation/documentation.md +++ b/src/pat/validation/documentation.md @@ -109,6 +109,22 @@ ValidationPattern.prototype.error_template = (message) => `${message}`; ``` + +### Form elements outside the form + +Input elements outside of form elements are fully supported. +pat-validation can handle structures like these: + +```html + +
+
+ +``` + +More information on the `form` attribute can be found at [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#form). + + ### Options reference > **_NOTE:_** The form inputs must have a `name` attribute, otherwise the diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index e4ed2d83d..cf8cebd23 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -72,6 +72,20 @@ class Pattern extends BasePattern { this.form.setAttribute("novalidate", ""); } + get inputs() { + // Return all inputs elements + return [...this.form.elements].filter((input) => + input.matches("input[name], select[name], textarea[name]"), + ); + } + + get disableable() { + // Return all elements, which should be disabled when there are errors. + return [...this.form.elements].filter((input) => + input.matches(this.options.disableSelector), + ); + } + async validate_all(event) { // Check all inputs. for (const input of this.inputs) { @@ -80,24 +94,19 @@ class Pattern extends BasePattern { } initialize_inputs() { - const previous_inputs = this.inputs || []; - this.inputs = [ - ...this.form.querySelectorAll("input[name], select[name], textarea[name]"), - ]; + const inputs = this.inputs; // Remove the listeners from inputs which are gone. - for (const input of previous_inputs) { - if (!this.inputs.includes(input)) { + for (const input of this._initialized_inputs || []) { + if (!inputs.includes(input)) { for (const event_type of ["input", "change", "blur"]) { this.remove_event_listener(input, event_type); } } } - this.disabled_elements = [ - ...this.form.querySelectorAll(this.options.disableSelector), - ]; + this._initialized_inputs = inputs; - for (const input of this.inputs) { + for (const input of inputs) { // Cancelable debouncer. const debouncer = utils.debounce((e) => { logger.debug("Checking input for event", input, e); @@ -141,8 +150,8 @@ class Pattern extends BasePattern { if ( input_options.equality && - this.form.querySelector(`[name=${input_options.equality}]`)?.value !== - input.value + this.inputs.find((_input) => _input.name === input_options.equality) + ?.value !== input.value ) { const message = input_options.message.equality || @@ -372,7 +381,9 @@ class Pattern extends BasePattern { let inputs = [input]; if (all_of_group) { // Get all inputs with the same name - e.g. radio buttons, checkboxes. - inputs = this.inputs.filter((it) => it.name === input.name); + inputs = [...this.form.elements].filter( + (_input) => _input.name === input.name, + ); } for (const it of inputs) { if (clear_state) { @@ -385,7 +396,7 @@ class Pattern extends BasePattern { // disable selector if (this.form.checkValidity()) { - for (const it of this.disabled_elements) { + for (const it of this.disableable) { if (it.disabled) { it.removeAttribute("disabled"); it.classList.remove("disabled"); @@ -404,12 +415,14 @@ class Pattern extends BasePattern { input, all_of_group: false, clear_state: false, - skip_event: true + skip_event: true, }); // Do not set a error message for a input group like radio buttons or // checkboxes where one has already been set. - const inputs = this.inputs.filter((it) => it.name === input.name); + const inputs = [...this.form.elements].filter( + (_input) => _input.name === input.name, + ); if (inputs.length > 1 && inputs.some((it) => !!it[KEY_ERROR_EL])) { // error message for input group already set. return; @@ -441,7 +454,7 @@ class Pattern extends BasePattern { input[KEY_ERROR_EL] = error_node; let did_disable = false; - for (const it of this.disabled_elements) { + for (const it of this.disableable) { // Disable for melements if they are not already disabled and which // do not have set the `formnovalidate` attribute, e.g. // ``. diff --git a/src/pat/validation/validation.test.js b/src/pat/validation/validation.test.js index f511a914d..707eb4ff8 100644 --- a/src/pat/validation/validation.test.js +++ b/src/pat/validation/validation.test.js @@ -540,6 +540,63 @@ describe("pat-validation", function () { expect(event.detail.dom).toBe(el); expect(event.detail.action).toBe("valid"); }); + + it("1.22 - Supports validation of inputs outside forms.", async function () { + document.body.innerHTML = ` + +
+
+ + `; + const form = document.querySelector(".pat-validation"); + const input = document.querySelector("[name=outside]"); + const button = document.querySelector("button"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + input.value = ""; + input.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(document.querySelectorAll("em.warning").length).toBe(1); + // Skip, as jsDOM does not support the `:invalid` or `:valid` + // pseudo selectors on forms. + //expect(form.matches(":invalid")).toBe(true); + expect(input.matches(":invalid")).toBe(true); + expect(button.matches(":disabled")).toBe(true); + }); + + it("1.22.1 - Supports equality checks with inputs outside forms.", async function () { + document.body.innerHTML = ` + +
+ +
+ `; + const form = document.querySelector(".pat-validation"); + const inside = document.querySelector("[name=inside]"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + inside.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(inside.matches(":invalid")).toBe(true); + expect(document.querySelector("em.warning").textContent).toBe("not equal"); + + inside.value = "secret"; + inside.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(inside.matches(":invalid")).toBe(false); + expect(document.querySelectorAll("em.warning").length).toBe(0); + }); }); describe("2 - required inputs", function () { From 0e65e5b9e66b0e92522385b1fc7a3f38bd963a62 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Tue, 13 May 2025 11:43:44 +0200 Subject: [PATCH 09/27] feat(pat-validation): Support definition of minimum or maximum number of selections. Assisted-by: Claude Opus 5.5 --- src/pat/validation/documentation.md | 5 + src/pat/validation/index.html | 153 +++++++++++++++- src/pat/validation/validation.js | 70 +++++++- src/pat/validation/validation.test.js | 242 ++++++++++++++++++++++++++ 4 files changed, 463 insertions(+), 7 deletions(-) diff --git a/src/pat/validation/documentation.md b/src/pat/validation/documentation.md index 62731c091..5d6fe8706 100644 --- a/src/pat/validation/documentation.md +++ b/src/pat/validation/documentation.md @@ -20,6 +20,7 @@ These extra validation rules are: - Equality checking between two fields (e.g. password confirmation). - Date and datetime validation for before and after a given date or another input field. +- Minimum and maximum number of checked, selected or filled-out fields. Most useful for checkboxes, but also works for text-inputs, selects and other form elements. ### HTML form validation framework integration. @@ -146,7 +147,11 @@ More information on the `form` attribute can be found at [MDN](https://developer | message-number | The error message for numbers. | This value must be a number. | String | | message-required | The error message for required fields. | This field is required. | String | | message-equality | The error message for fields required to be equal | is not equal to %{attribute} | String | +| message-min-values | The error message when the minimum 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 been exceeded. | You need to select at most %{count} item(s). | String | | equality | Field-specific extra rule. The name of another input this input should equal to (useful for password confirmation). | | String | | not-after | Field-specific extra rule. A lower time limit restriction for date and datetime fields. | | CSS Selector or a ISO8601 date string. | | not-before | Field-specific extra rule. An upper time limit restriction for date and datetime fields. | | CSS Selector or a ISO8601 date 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) | | delay | Time in milliseconds before validation starts to avoid validating while typing. | 100 | Integer | diff --git a/src/pat/validation/index.html b/src/pat/validation/index.html index 595844667..8dd852e7f 100644 --- a/src/pat/validation/index.html +++ b/src/pat/validation/index.html @@ -115,8 +115,6 @@ yellow -
- @@ -250,6 +247,154 @@ +

Demo with max-values / min-values support

+
+
+ Multi select + +
+ +
+ Multiple checkboxes + + + + +
+ +
+ Demo with mixed inputs and max/min values support. +
+ +
+
+ + + + +
+
+ + + +
+
+
+ + +
+
+
max_values) { + this.set_error({ + input: input, + msg: input_options.message["max-values"], + max: max_values, + }) + } + if (min_values !== null && number_values < min_values) { + this.set_error({ + input: input, + msg: input_options.message["min-values"], + min: min_values, + }) + } } if (!validity_state.customError) { @@ -351,15 +411,19 @@ class Pattern extends BasePattern { if (attribute) { msg = msg.replace(/%{attribute}/g, attribute); } - if (min) { + if (min !== null) { msg = msg.replace(/%{count}/g, min); } - if (max) { + if (max !== null) { msg = msg.replace(/%{count}/g, max); } msg = msg.replace(/%{value}/g, JSON.stringify(input.value)); - input.setCustomValidity(msg); + // Set the error state the input itself and on all siblings, if any. + const inputs = [...this.form.elements].filter((_input) => _input.name === input.name); + for (const _input of inputs) { + _input.setCustomValidity(msg); + } // Store the error message on the input. // Hidden inputs do not participate in validation but we need this // (e.g. styled date input). diff --git a/src/pat/validation/validation.test.js b/src/pat/validation/validation.test.js index 707eb4ff8..e59e8c44b 100644 --- a/src/pat/validation/validation.test.js +++ b/src/pat/validation/validation.test.js @@ -1865,4 +1865,246 @@ describe("pat-validation", function () { expect(spy_check_input).toHaveBeenCalledTimes(1); }); }); + + describe("10 - min/max value validation", function () { + it("10.1 - validate min and max number of checked checkboxes", async function () { + document.body.innerHTML = ` + +
+ + + + +
+
+ `; + + const form = document.querySelector("form"); + const check1 = form.querySelector("[name=check][value='1']"); + const check2 = form.querySelector("[name=check][value='2']"); + const check3 = form.querySelector("[name=check][value='3']"); + const check4 = form.querySelector("[name=check][value='4']"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + check1.checked = true; + check1.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(check1.matches(":invalid")).toBe(true); + expect(check2.matches(":invalid")).toBe(true); + expect(check3.matches(":invalid")).toBe(true); + expect(check4.matches(":invalid")).toBe(true); + expect(form.querySelectorAll("em.warning").length).toBe(1); + expect(form.querySelectorAll("em.warning")[0].textContent).toBe( + "Please select at least 2 options" + ); + + check2.checked = true; + check2.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(check1.matches(":invalid")).toBe(false); + expect(check2.matches(":invalid")).toBe(false); + expect(check3.matches(":invalid")).toBe(false); + expect(check4.matches(":invalid")).toBe(false); + expect(form.querySelectorAll("em.warning").length).toBe(0); + + check3.checked = true; + check3.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(check1.matches(":invalid")).toBe(false); + expect(check2.matches(":invalid")).toBe(false); + expect(check3.matches(":invalid")).toBe(false); + expect(check4.matches(":invalid")).toBe(false); + expect(form.querySelectorAll("em.warning").length).toBe(0); + + check4.checked = true; + check4.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(check1.matches(":invalid")).toBe(true); + expect(check2.matches(":invalid")).toBe(true); + expect(check3.matches(":invalid")).toBe(true); + expect(check4.matches(":invalid")).toBe(true); + expect(form.querySelectorAll("em.warning").length).toBe(1); + expect(form.querySelectorAll("em.warning")[0].textContent).toBe( + "Please select at most 3 options" + ); + + check4.checked = false; + check4.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(check1.matches(":invalid")).toBe(false); + expect(check2.matches(":invalid")).toBe(false); + expect(check3.matches(":invalid")).toBe(false); + expect(check4.matches(":invalid")).toBe(false); + expect(form.querySelectorAll("em.warning").length).toBe(0); + }); + + it("10.2 - validate min and max number with mixed inputs", async function () { + document.body.innerHTML = ` +
+
+ + + + + +
+
+ `; + + const form = document.querySelector("form"); + const id1 = form.querySelector("#i1"); + const id2 = form.querySelector("#i2"); + const id3 = form.querySelector("#i3"); + const id31 = form.querySelector("#i31"); + const id4 = form.querySelector("#i4"); + const id5 = form.querySelector("#i5"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + id1.checked = true; + id1.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(id1.matches(":invalid")).toBe(true); + expect(id2.matches(":invalid")).toBe(true); + expect(id3.matches(":invalid")).toBe(true); + expect(id4.matches(":invalid")).toBe(true); + expect(id5.matches(":invalid")).toBe(true); + expect(form.querySelectorAll("em.warning").length).toBe(1); + expect(form.querySelectorAll("em.warning")[0].textContent).toBe( + "Please select at least 2 options" + ); + + id2.checked = true; + id2.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(id1.matches(":invalid")).toBe(false); + expect(id2.matches(":invalid")).toBe(false); + expect(id3.matches(":invalid")).toBe(false); + expect(id4.matches(":invalid")).toBe(false); + expect(id5.matches(":invalid")).toBe(false); + expect(form.querySelectorAll("em.warning").length).toBe(0); + + id31.selected = true; + id3.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(id1.matches(":invalid")).toBe(false); + expect(id2.matches(":invalid")).toBe(false); + expect(id3.matches(":invalid")).toBe(false); + expect(id4.matches(":invalid")).toBe(false); + expect(id5.matches(":invalid")).toBe(false); + expect(form.querySelectorAll("em.warning").length).toBe(0); + + id4.value = "okay"; + id4.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(id1.matches(":invalid")).toBe(true); + expect(id2.matches(":invalid")).toBe(true); + expect(id3.matches(":invalid")).toBe(true); + expect(id4.matches(":invalid")).toBe(true); + expect(id5.matches(":invalid")).toBe(true); + expect(form.querySelectorAll("em.warning").length).toBe(1); + expect(form.querySelectorAll("em.warning")[0].textContent).toBe( + "Please select at most 3 options" + ); + + id2.checked = false; + id2.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(id1.matches(":invalid")).toBe(false); + expect(id2.matches(":invalid")).toBe(false); + expect(id3.matches(":invalid")).toBe(false); + expect(id4.matches(":invalid")).toBe(false); + expect(id5.matches(":invalid")).toBe(false); + expect(form.querySelectorAll("em.warning").length).toBe(0); + + id5.value = "okay"; + id4.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(id1.matches(":invalid")).toBe(true); + expect(id2.matches(":invalid")).toBe(true); + expect(id3.matches(":invalid")).toBe(true); + expect(id4.matches(":invalid")).toBe(true); + expect(id5.matches(":invalid")).toBe(true); + expect(form.querySelectorAll("em.warning").length).toBe(1); + expect(form.querySelectorAll("em.warning")[0].textContent).toBe( + "Please select at most 3 options" + ); + + id4.value = ""; + id4.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(id1.matches(":invalid")).toBe(false); + expect(id2.matches(":invalid")).toBe(false); + expect(id3.matches(":invalid")).toBe(false); + expect(id4.matches(":invalid")).toBe(false); + expect(id5.matches(":invalid")).toBe(false); + expect(form.querySelectorAll("em.warning").length).toBe(0); + }); + + it("10.3 - supports a value of 0 and replaces %{count}", async function () { + document.body.innerHTML = ` +
+
+ + +
+
+ `; + + const form = document.querySelector("form"); + const check1 = form.querySelector("[name=check][value='1']"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + check1.checked = true; + check1.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(check1.matches(":invalid")).toBe(true); + expect(form.querySelectorAll("em.warning").length).toBe(1); + expect(form.querySelector("em.warning").textContent).toBe( + "You need to select at most 0 item(s)." + ); + + check1.checked = false; + check1.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(check1.matches(":invalid")).toBe(false); + expect(form.querySelectorAll("em.warning").length).toBe(0); + }); + }); + }); From 90df03695bb6c55f8c5b07dea54a8fa2b9c12ca6 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Tue, 13 May 2025 16:58:14 +0200 Subject: [PATCH 10/27] fix(pat-validation): Put error messages always at the end of a group of inputs with the same name. Assisted-by: Claude Opus 5.5 --- src/pat/validation/documentation.md | 4 +-- src/pat/validation/validation.js | 15 ++++----- src/pat/validation/validation.test.js | 44 +++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 11 deletions(-) diff --git a/src/pat/validation/documentation.md b/src/pat/validation/documentation.md index 5d6fe8706..54380c147 100644 --- a/src/pat/validation/documentation.md +++ b/src/pat/validation/documentation.md @@ -89,10 +89,10 @@ In addition both the input element and its label will get an `warning` class. ``` -Checkboxes and radio buttons are treated differently: if they are contained in a fieldset with class `checklist` error messages are added at the end of the fieldset. +Checkboxes and radio buttons are treated differently: The error message is always set after the last element of the inputs with the same name. If that input is wrapped in a label, the error message is set after the label. ```html -
+
diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index d5931cb22..604d5ea0e 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -506,15 +506,12 @@ class Pattern extends BasePattern { this.error_template(validation_message), ).firstChild; - let fieldset; - if (input.type === "radio" || input.type === "checkbox") { - fieldset = input.closest("fieldset.pat-checklist"); - } - if (fieldset) { - fieldset.append(error_node); - } else { - input.after(error_node); - } + // Put error message after the erroneous input or - in case of + // multiple inputs with the same name - after the last one of the + // group. If the input is wrapped in a label, put the error message + // after the label. + const last_input = inputs.pop(); + (last_input.closest("label") || last_input).after(error_node); input[KEY_ERROR_EL] = error_node; let did_disable = false; diff --git a/src/pat/validation/validation.test.js b/src/pat/validation/validation.test.js index e59e8c44b..966d3059d 100644 --- a/src/pat/validation/validation.test.js +++ b/src/pat/validation/validation.test.js @@ -597,6 +597,50 @@ describe("pat-validation", function () { expect(inside.matches(":invalid")).toBe(false); expect(document.querySelectorAll("em.warning").length).toBe(0); }); + + it("1.23 - Puts the warning at the end of same-name inputs.", async function () { + document.body.innerHTML = ` +
+ + + +
+ `; + const form = document.querySelector(".pat-validation"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + form.dispatchEvent(events.submit_event()); + await utils.timeout(1); // wait a tick for async to settle. + + const warning = form.querySelector("em.warning"); + expect(warning).toBeTruthy(); + expect(warning.matches("input:nth-child(3) + em.warning")).toBe(true); + }); + + it("1.23.1 - Puts the warning after the label of label-wrapped inputs.", async function () { + document.body.innerHTML = ` +
+
+ + +
+
+ `; + const form = document.querySelector(".pat-validation"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + form.dispatchEvent(events.submit_event()); + await utils.timeout(1); // wait a tick for async to settle. + + const warnings = form.querySelectorAll("em.warning"); + expect(warnings.length).toBe(1); + expect(warnings[0].parentElement.tagName).toBe("FIELDSET"); + expect(warnings[0].matches("label:nth-child(2) + em.warning")).toBe(true); + }); }); describe("2 - required inputs", function () { From b80ac3e944368ac071986acb4009d6937e9829ac Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 15:47:44 +0100 Subject: [PATCH 11/27] maint(docs): Add ADR 0005 on event delegation with focusout in pat-validation. Assisted-by: Claude Opus 5.5 --- ...lidation-event-delegation-with-focusout.md | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 docs/adr/0005-pat-validation-event-delegation-with-focusout.md diff --git a/docs/adr/0005-pat-validation-event-delegation-with-focusout.md b/docs/adr/0005-pat-validation-event-delegation-with-focusout.md new file mode 100644 index 000000000..b2e4ced80 --- /dev/null +++ b/docs/adr/0005-pat-validation-event-delegation-with-focusout.md @@ -0,0 +1,57 @@ +# 0005 pat-validation: Event delegation on the document with focusout + +Status: Accepted (2026-11-27) + +## Context + +pat-validation used to register `input`, `change` and `blur` event listeners on +each input of the form when the pattern was initialized, and re-registered them +on `pat-update` events. + +This did not support: + +- Dynamic forms, where inputs are added after initialization without a + `pat-update` event. +- Inputs outside of the form element, which are associated with the form via + the `form` attribute. + +Event delegation needs bubbling events. `input` and `change` bubble, but `blur` +does not. `focusout` is the bubbling equivalent of `blur`. + +Some patterns hide the original input and show a proxy widget instead, e.g. +pat-date-picker, pat-datetime-picker and pat-auto-suggest. They dispatch a +synthetic event on the original input to trigger the validation when the user +leaves the widget without making a choice. They used to dispatch a `blur` +event. + +## Decision + +- pat-validation registers one `input`, one `change` and one `focusout` event + listener per pattern instance on the `document`. +- The handler only handles events whose target belongs to the form + (`input.form === this.form`) and is one of the form's inputs. +- The list of inputs is not cached but computed from `form.elements` when + needed, so that inputs added later and inputs outside the form are included. +- The validation is debounced per input, so that multiple inputs can be + validated in parallel. +- The event listeners are registered with the instance scoped + `BasePattern.add_event_listener` (see ADR 0004) and are removed by + `BasePattern.destroy`. +- Patterns which want to trigger the validation of an input dispatch a + bubbling `focusout` event (`events.focusout_event()`) on that input, not a + `blur` event. pat-date-picker, pat-datetime-picker and pat-auto-suggest were + changed accordingly. + +## Consequences + +- Dynamic forms and inputs outside the form are supported without + re-initialization. +- A synthetic `blur` event does not trigger the validation anymore. Third + party code and patterns which dispatch `blur` to trigger the validation must + dispatch `focusout` instead. +- Every `input`, `change` and `focusout` event in the document passes the + filter of every pat-validation instance. The filter is cheap. +- The pattern is destroyed automatically when the form is removed from the + DOM (see ADR 0001), which also removes the listeners from the document. +- The inputs do not get event listeners of their own. Re-initializing the + inputs on `pat-update` is not needed anymore. From 42f69f150de039eb4fd1b5324cb384b2a45b1b76 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Thu, 26 Nov 2026 02:37:40 +0100 Subject: [PATCH 12/27] feat(pat-validation): Support dynamic forms. 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 --- src/pat/auto-suggest/auto-suggest.js | 6 +- src/pat/date-picker/date-picker.js | 6 +- src/pat/datetime-picker/datetime-picker.js | 4 +- .../datetime-picker/datetime-picker.test.js | 25 ++++ src/pat/validation/documentation.md | 6 + src/pat/validation/validation.js | 99 ++++++++------ src/pat/validation/validation.test.js | 128 +++++++++++++++--- 7 files changed, 210 insertions(+), 64 deletions(-) diff --git a/src/pat/auto-suggest/auto-suggest.js b/src/pat/auto-suggest/auto-suggest.js index a322dcb70..1a484cea5 100644 --- a/src/pat/auto-suggest/auto-suggest.js +++ b/src/pat/auto-suggest/auto-suggest.js @@ -122,9 +122,9 @@ export default Base.extend({ const val = $sel2.select2("val"); if (val?.length === 0) { // catches "" and [] - // blur the input field so that pat-validate can kick in when - // nothing was selected. - this.el.dispatchEvent(events.blur_event()); + // focus-out the input field so that pat-validate can kick in + // when nothing was selected. + this.el.dispatchEvent(events.focusout_event()); } }; this.$el.on("select2-close", initiate_empty_check.bind(this)); diff --git a/src/pat/date-picker/date-picker.js b/src/pat/date-picker/date-picker.js index 3c885047c..c283591a3 100644 --- a/src/pat/date-picker/date-picker.js +++ b/src/pat/date-picker/date-picker.js @@ -178,9 +178,9 @@ export default Base.extend({ onSelect: () => this.dispatch_change_event(), onClose: () => { if (this.options.behavior === "styled" && !this.el.value) { - // blur the input field so that pat-validate can kick in when - // nothing was selected. - el.dispatchEvent(events.blur_event()); + // focus-out the input field so that pat-validate can kick + // in when nothing was selected. + el.dispatchEvent(events.focusout_event()); } }, }; diff --git a/src/pat/datetime-picker/datetime-picker.js b/src/pat/datetime-picker/datetime-picker.js index 6c8b13101..45ca48c73 100644 --- a/src/pat/datetime-picker/datetime-picker.js +++ b/src/pat/datetime-picker/datetime-picker.js @@ -117,7 +117,9 @@ export default Base.extend({ for (const input of [this.el_date, this.el_time]) { input.addEventListener("blur", (event) => { if (!el_wrapper.contains(event.relatedTarget)) { - el.dispatchEvent(events.blur_event()); + // focus-out the input field so that pat-validate can kick + // in when nothing was selected. + el.dispatchEvent(events.focusout_event()); } }); } diff --git a/src/pat/datetime-picker/datetime-picker.test.js b/src/pat/datetime-picker/datetime-picker.test.js index 4998c3ba7..d3fe15767 100644 --- a/src/pat/datetime-picker/datetime-picker.test.js +++ b/src/pat/datetime-picker/datetime-picker.test.js @@ -285,4 +285,29 @@ describe("pat-datetime-picker", function () { expect(end.value).toBe("2021-03-15T12:34"); }, ); + + it("dispatches a bubbling focusout event on the original input when focus leaves the widget", async () => { + // We mocking as if we're not supporting input type date. + jest.spyOn(utils, "checkInputSupport").mockImplementation(() => false); + + document.body.innerHTML = ` + + + `; + const el = document.querySelector(".pat-datetime-picker"); + pattern.init(el); + await utils.timeout(1); // wait a tick for async to settle. + + const targets = []; + document.addEventListener("focusout", (e) => targets.push(e.target)); + + const el_time = document.querySelector("input[type=time]"); + el_time.dispatchEvent( + new FocusEvent("blur", { + relatedTarget: document.querySelector("#outside"), + }), + ); + + expect(targets).toContain(el); + }); }); diff --git a/src/pat/validation/documentation.md b/src/pat/validation/documentation.md index 54380c147..6195d7f35 100644 --- a/src/pat/validation/documentation.md +++ b/src/pat/validation/documentation.md @@ -126,6 +126,12 @@ pat-validation can handle structures like these: More information on the `form` attribute can be found at [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#form). +### Dynamic forms + +pat-validation supports dynamic forms where form elements are added after the Pattern was initialized. +There is no need to re-initialize the pattern or to dispatch a special event. + + ### Options reference > **_NOTE:_** The form inputs must have a `name` attribute, otherwise the diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index 604d5ea0e..12de1f09d 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -1,6 +1,5 @@ // Patterns validate - Form vlidation import "../../core/polyfills"; // SubmitEvent.submitter for Safari < 15.4 and jsDOM -import $ from "jquery"; import { BasePattern } from "../../core/basepattern"; import Parser from "../../core/parser"; import dom from "../../core/dom"; @@ -20,7 +19,10 @@ parser.addArgument("message-min", ""); // "This value must be greater than or eq parser.addArgument("message-number", ""); // "This value must be a number" parser.addArgument("message-required", ""); // "This field is required" parser.addArgument("message-equality", "is not equal to %{attribute}."); -parser.addArgument("message-min-values", "You need to select at least %{count} item(s)."); +parser.addArgument( + "message-min-values", + "You need to select at least %{count} item(s).", +); parser.addArgument("message-max-values", "You need to select at most %{count} item(s)."); parser.addArgument("not-after", null); parser.addArgument("not-before", null); @@ -66,10 +68,54 @@ class Pattern extends BasePattern { { capture: true }, ); - this.initialize_inputs(); - $(this.form).on("pat-update", () => { - this.initialize_inputs(); - }); + // Input debouncer map: + // - key: input element + // - value: debouncer function + // 1) We want do debounce the validation checks to avoid validating + // while typing. + // 2) We want to debounce the input events individually, so that we can + // do multiple checks in parallel and show multiple errors at once. + const input_debouncer_map = new Map(); + const debounce_filter = (e) => { + const input = e.target; + if (input?.form !== this.form || !this.inputs.includes(input)) { + // Ignore events from other forms or from elements which are + // not inputs. + return; + } + + if (!input_debouncer_map.has(input)) { + // Create a new cancelable debouncer for this input. + input_debouncer_map.set( + input, + utils.debounce((e) => { + logger.debug("Checking input for event", input, e); + this.check_input({ input: input, event: e }); + }, this.options.delay), + ); + } + + // Get the debouncer for this input. + const debouncer = input_debouncer_map.get(input); + // Debounce the validation check. + debouncer(e); + }; + + this.add_event_listener(document, "input", "input--validator", debounce_filter); + + this.add_event_listener( + document, + "change", + "change--validator", + debounce_filter, + ); + + this.add_event_listener( + document, + "focusout", + "focusout--validator", + debounce_filter, + ); // Set ``novalidate`` attribute to disable the browser's validation // bubbles but not disable the validation API. @@ -97,35 +143,6 @@ class Pattern extends BasePattern { } } - initialize_inputs() { - const inputs = this.inputs; - - // Remove the listeners from inputs which are gone. - for (const input of this._initialized_inputs || []) { - if (!inputs.includes(input)) { - for (const event_type of ["input", "change", "blur"]) { - this.remove_event_listener(input, event_type); - } - } - } - this._initialized_inputs = inputs; - - for (const input of inputs) { - // Cancelable debouncer. - const debouncer = utils.debounce((e) => { - logger.debug("Checking input for event", input, e); - this.check_input({ input: input, event: e }); - }, this.options.delay); - - // Registering again under the same name replaces the listener. - for (const event_type of ["input", "change", "blur"]) { - this.add_event_listener(input, event_type, event_type, (e) => - debouncer(e), - ); - } - } - } - async check_input({ input, // Input to check. event = null, // Optional event which triggered the check. @@ -282,9 +299,9 @@ class Pattern extends BasePattern { // Filter for siblings with same name. if ( // Keep only inputs with same name - _inp.name !== input.name + _inp.name !== input.name || // Skip all form elements which are no input elements - || ! ["INPUT", "SELECT", "TEXTAREA"].includes(_inp.tagName) + !["INPUT", "SELECT", "TEXTAREA"].includes(_inp.tagName) ) { continue; } @@ -314,14 +331,14 @@ class Pattern extends BasePattern { input: input, msg: input_options.message["max-values"], max: max_values, - }) + }); } if (min_values !== null && number_values < min_values) { this.set_error({ input: input, msg: input_options.message["min-values"], min: min_values, - }) + }); } } @@ -420,7 +437,9 @@ class Pattern extends BasePattern { msg = msg.replace(/%{value}/g, JSON.stringify(input.value)); // Set the error state the input itself and on all siblings, if any. - const inputs = [...this.form.elements].filter((_input) => _input.name === input.name); + const inputs = [...this.form.elements].filter( + (_input) => _input.name === input.name, + ); for (const _input of inputs) { _input.setCustomValidity(msg); } diff --git a/src/pat/validation/validation.test.js b/src/pat/validation/validation.test.js index 966d3059d..0ba21e0c1 100644 --- a/src/pat/validation/validation.test.js +++ b/src/pat/validation/validation.test.js @@ -1,4 +1,3 @@ -import $ from "jquery"; import Pattern, { parser } from "./validation"; import events, { event_listener_map } from "../../core/events"; import utils from "../../core/utils"; @@ -479,7 +478,7 @@ describe("pat-validation", function () { const instance = new Pattern(el); await events.await_pattern_init(instance); - document.querySelector("[name=i1]").dispatchEvent(events.blur_event()); + document.querySelector("[name=i1]").dispatchEvent(events.focusout_event()); await utils.timeout(1); // wait a tick for async to settle. expect(el.querySelectorAll("em.warning").length).toBe(2); @@ -500,7 +499,7 @@ describe("pat-validation", function () { const instance = new Pattern(el); await events.await_pattern_init(instance); - document.querySelector("[name=i1]").dispatchEvent(events.blur_event()); + document.querySelector("[name=i1]").dispatchEvent(events.focusout_event()); await utils.timeout(1); // wait a tick for async to settle. expect(el.querySelectorAll("em.warning").length).toBe(1); @@ -641,6 +640,94 @@ describe("pat-validation", function () { expect(warnings[0].parentElement.tagName).toBe("FIELDSET"); expect(warnings[0].matches("label:nth-child(2) + em.warning")).toBe(true); }); + + it("1.24 - Supports dynamic forms.", async function () { + document.body.innerHTML = ` +
+ +
+ `; + const form = document.querySelector(".pat-validation"); + const input1 = form.querySelector("[name=input1]"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + form.dispatchEvent(events.submit_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(document.querySelectorAll("em.warning").length).toBe(1); + + input1.value = "ok"; + input1.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(document.querySelectorAll("em.warning").length).toBe(0); + + const input2 = document.createElement("input"); + input2.name = "input2"; + input2.required = true; + form.appendChild(input2); + + form.dispatchEvent(events.submit_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(document.querySelectorAll("em.warning").length).toBe(1); + expect(document.querySelector("em.warning").matches("input[name=input2] + em.warning")).toBe(true); + }); + + it("1.24.1 - Passes the triggering event to check_input.", async function () { + document.body.innerHTML = ` +
+ +
+ `; + const form = document.querySelector(".pat-validation"); + const input1 = form.querySelector("[name=input1]"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + const spy = jest.spyOn(instance, "check_input"); + const event = events.change_event(); + input1.dispatchEvent(event); + await utils.timeout(1); // wait a tick for async to settle. + + expect(spy).toHaveBeenCalledTimes(1); + expect(spy.mock.calls[0][0].input).toBe(input1); + expect(spy.mock.calls[0][0].event).toBe(event); + }); + + it("1.24.2 - Removes the event listeners on destroy.", async function () { + document.body.innerHTML = ` +
+ +
+ `; + const form = document.querySelector(".pat-validation"); + const input1 = form.querySelector("[name=input1]"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + instance.destroy(); + + const spy = jest.spyOn(instance, "check_input"); + input1.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(spy).not.toHaveBeenCalled(); + expect(document.querySelectorAll("em.warning").length).toBe(0); + + // Submit is not validated anymore. + const submit_event = events.submit_event(); + form.dispatchEvent(submit_event); + await utils.timeout(1); // wait a tick for async to settle. + + expect(spy).not.toHaveBeenCalled(); + expect(submit_event.defaultPrevented).toBe(false); + expect(document.querySelectorAll("em.warning").length).toBe(0); + }); }); describe("2 - required inputs", function () { @@ -1859,6 +1946,11 @@ describe("pat-validation", function () { document.body.innerHTML = ""; }); + const document_listener_ids = (instance) => + [...(event_listener_map.get(document)?.keys() || [])].filter((id) => + id.startsWith(`validation--${instance.uuid}--`), + ); + it("9.1 - Removing the form removes all listeners.", async function () { document.body.innerHTML = `
@@ -1871,42 +1963,44 @@ describe("pat-validation", function () { const instance = new Pattern(el); await events.await_pattern_init(instance); + // The submit listener on the form. expect(event_listener_map.get(el).size).toBe(1); - expect(event_listener_map.get(i1).size).toBe(3); - expect(event_listener_map.get(i2).size).toBe(3); + // No listeners on the inputs - events are delegated. + expect(event_listener_map.has(i1)).toBe(false); + expect(event_listener_map.has(i2)).toBe(false); + // The input, change and focusout listeners on the document. + expect(document_listener_ids(instance).length).toBe(3); el.remove(); await utils.timeout(1); expect(instance.destroyed).toBe(true); expect(event_listener_map.has(el)).toBe(false); - expect(event_listener_map.has(i1)).toBe(false); - expect(event_listener_map.has(i2)).toBe(false); + expect(document_listener_ids(instance).length).toBe(0); }); - it("9.2 - Re-initializing the inputs does not duplicate listeners and removes them from removed inputs.", async function () { + it("9.2 - Inputs added later are validated without own listeners.", async function () { document.body.innerHTML = ` -
`; const el = document.querySelector(".pat-validation"); - const [i1, i2] = el.querySelectorAll("[name]"); const instance = new Pattern(el); await events.await_pattern_init(instance); - // Remove the first input, so that the second one changes its position. - i1.remove(); - $(el).trigger("pat-update"); - - expect(event_listener_map.has(i1)).toBe(false); - expect(event_listener_map.get(i2).size).toBe(3); + const i2 = document.createElement("input"); + i2.name = "i2"; + i2.required = true; + el.appendChild(i2); const spy_check_input = jest.spyOn(instance, "check_input"); - i2.dispatchEvent(new Event("input")); + i2.dispatchEvent(events.input_event()); await utils.timeout(instance.options.delay + 1); // wait for the debouncer. + expect(spy_check_input).toHaveBeenCalledTimes(1); + expect(spy_check_input.mock.calls[0][0].input).toBe(i2); + expect(event_listener_map.has(i2)).toBe(false); }); }); From 9a62ad42479c9e9d0b82c62bf9bc883bba3628a6 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 15:56:46 +0100 Subject: [PATCH 13/27] fixup! feat(pat-validation): Support dynamic forms. 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 --- src/pat/validation/validation.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index 12de1f09d..07f5459ab 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -75,7 +75,9 @@ class Pattern extends BasePattern { // while typing. // 2) We want to debounce the input events individually, so that we can // do multiple checks in parallel and show multiple errors at once. - const input_debouncer_map = new Map(); + // A WeakMap does not keep inputs alive which were removed from the + // form. + const input_debouncer_map = new WeakMap(); const debounce_filter = (e) => { const input = e.target; if (input?.form !== this.form || !this.inputs.includes(input)) { From bf844bbfd36c3afc83ab538ffbb845deb8fce0ab Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Thu, 26 Nov 2026 02:38:46 +0100 Subject: [PATCH 14/27] fix(pat-validation): Support the combination of multiple custom validation 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 --- src/pat/validation/validation.js | 26 ++++--- src/pat/validation/validation.test.js | 97 +++++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 8 deletions(-) diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index 07f5459ab..b3ac9b8fb 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -184,7 +184,12 @@ class Pattern extends BasePattern { msg: message, attribute: input_options.equality, }); - } else if (input_options.not.after || input_options.not.before) { + } + + if ( + !validity_state.customError && // No error from previous checks. + (input_options.not.after || input_options.not.before) + ) { const msg = input_options.message.date || input_options.message.datetime; const msg_default_not_before = "The date must be after %{attribute}"; const msg_default_not_after = "The date must be before %{attribute}"; @@ -286,7 +291,12 @@ class Pattern extends BasePattern { logger.debug("Check `no-before` input.", not_after_el); await this.check_input({ input: not_before_el, stop: true }); } - } else if (input_options.minValues || input_options.maxValues) { + } + + if ( + !validity_state.customError && // No error from previous checks. + (input_options.minValues || input_options.maxValues) + ) { const min_values = input_options.minValues === null ? null @@ -343,12 +353,6 @@ class Pattern extends BasePattern { }); } } - - if (!validity_state.customError) { - // No error to handle. Return. - this.remove_error({ input }); - return; - } } else { // Default error cases with custom messages. @@ -409,6 +413,12 @@ class Pattern extends BasePattern { } } + if (validity_state.valid) { + // No error to handle. Remove eventual error and return. + this.remove_error({ input }); + return; + } + if (event?.type === "submit") { // Do not submit in error case and prevent other handlers to take action. event.preventDefault(); diff --git a/src/pat/validation/validation.test.js b/src/pat/validation/validation.test.js index 0ba21e0c1..89c3efe95 100644 --- a/src/pat/validation/validation.test.js +++ b/src/pat/validation/validation.test.js @@ -728,6 +728,103 @@ describe("pat-validation", function () { expect(submit_event.defaultPrevented).toBe(false); expect(document.querySelectorAll("em.warning").length).toBe(0); }); + + it("1.25 - Can combine multiple custom validation rules.", async function () { + document.body.innerHTML = ` +
+
+ + +
+ +
+ `; + const form = document.querySelector(".pat-validation"); + const input1 = document.querySelector("#i1"); + const input2 = document.querySelector("#i2"); + const input3 = document.querySelector("#i3"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + input1.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + // form is invalid due to input1's required attribute + expect(input1.matches(":invalid")).toBe(true); + expect(document.querySelectorAll("em.warning").length).toBe(1); + expect(document.querySelectorAll("em.warning")[0].textContent).toBe( + "is required" + ); + + input1.value = "ok"; + input1.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + // form is invalid due to input1's equality constraint + expect(input1.matches(":invalid")).toBe(true); + expect(document.querySelectorAll("em.warning").length).toBe(1); + expect(document.querySelectorAll("em.warning")[0].textContent).toBe( + "not equal" + ); + + input3.value = "ok"; + input1.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + // form is invalid due to input1's equality constraint + expect(input1.matches(":invalid")).toBe(true); + expect(document.querySelectorAll("em.warning").length).toBe(1); + expect(document.querySelectorAll("em.warning")[0].textContent).toBe( + "too few" + ); + + input2.value = "ok"; + form.dispatchEvent(events.submit_event()); + await utils.timeout(1); // wait a tick for async to settle. + + // form is now valid. + expect(input1.matches(":invalid")).toBe(false); + expect(document.querySelectorAll("em.warning").length).toBe(0); + }); + + it("1.25.1 - Does not overwrite a previous custom validation error.", async function () { + document.body.innerHTML = ` +
+ + +
+ `; + const form = document.querySelector(".pat-validation"); + const input_a = form.querySelector("[name=a]"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + input_a.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(input_a.matches(":invalid")).toBe(true); + expect(form.querySelectorAll("em.warning").length).toBe(1); + expect(form.querySelector("em.warning").textContent).toBe("not equal"); + }); }); describe("2 - required inputs", function () { From 4de3525c1b9e3448a2f8d0bb2643038da8ef2ee5 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Wed, 14 May 2025 22:52:05 +0200 Subject: [PATCH 15/27] tech(pat-validation): Generalize the method to retrieve siblings. --- src/pat/validation/validation.js | 30 +++++++++--------------------- 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index b3ac9b8fb..a0581f7f4 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -138,6 +138,11 @@ class Pattern extends BasePattern { ); } + siblings(input) { + // Get all siblings of an input with the same name. + return this.inputs.filter((_input) => _input.name === input.name); + } + async validate_all(event) { // Check all inputs. for (const input of this.inputs) { @@ -307,17 +312,7 @@ class Pattern extends BasePattern { : parseInt(input_options.maxValues, 10); let number_values = 0; - for (const _inp of this.form.elements) { - // Filter for siblings with same name. - if ( - // Keep only inputs with same name - _inp.name !== input.name || - // Skip all form elements which are no input elements - !["INPUT", "SELECT", "TEXTAREA"].includes(_inp.tagName) - ) { - continue; - } - + for (const _inp of this.siblings(input)) { // Check if checkboxes or radios are checked ... if (_inp.type === "checkbox" || _inp.type === "radio") { if (_inp.checked) { @@ -449,10 +444,7 @@ class Pattern extends BasePattern { msg = msg.replace(/%{value}/g, JSON.stringify(input.value)); // Set the error state the input itself and on all siblings, if any. - const inputs = [...this.form.elements].filter( - (_input) => _input.name === input.name, - ); - for (const _input of inputs) { + for (const _input of this.siblings(input)) { _input.setCustomValidity(msg); } // Store the error message on the input. @@ -476,9 +468,7 @@ class Pattern extends BasePattern { let inputs = [input]; if (all_of_group) { // Get all inputs with the same name - e.g. radio buttons, checkboxes. - inputs = [...this.form.elements].filter( - (_input) => _input.name === input.name, - ); + inputs = this.siblings(input); } for (const it of inputs) { if (clear_state) { @@ -515,9 +505,7 @@ class Pattern extends BasePattern { // Do not set a error message for a input group like radio buttons or // checkboxes where one has already been set. - const inputs = [...this.form.elements].filter( - (_input) => _input.name === input.name, - ); + const inputs = this.siblings(input); if (inputs.length > 1 && inputs.some((it) => !!it[KEY_ERROR_EL])) { // error message for input group already set. return; From f4519033e9ed1d432c4001a5a6dfbfd89042500d Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Mon, 19 May 2025 13:58:33 +0200 Subject: [PATCH 16/27] tech(pat-validation): Cleanup - better variable names. --- src/pat/validation/validation.js | 42 ++++++++++++++++---------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index a0581f7f4..01774fd4b 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -131,7 +131,7 @@ class Pattern extends BasePattern { ); } - get disableable() { + get disableables() { // Return all elements, which should be disabled when there are errors. return [...this.form.elements].filter((input) => input.matches(this.options.disableSelector), @@ -312,23 +312,23 @@ class Pattern extends BasePattern { : parseInt(input_options.maxValues, 10); let number_values = 0; - for (const _inp of this.siblings(input)) { + for (const _input of this.siblings(input)) { // Check if checkboxes or radios are checked ... - if (_inp.type === "checkbox" || _inp.type === "radio") { - if (_inp.checked) { + if (_input.type === "checkbox" || _input.type === "radio") { + if (_input.checked) { number_values++; } continue; } // Select, if select is selected. - if (_inp.tagName === "SELECT") { - number_values += _inp.selectedOptions.length; + if (_input.tagName === "SELECT") { + number_values += _input.selectedOptions.length; continue; } // For the rest a value must be set. - if (_inp.value === 0 || _inp.value) { + if (_input.value === 0 || _input.value) { number_values++; } } @@ -470,21 +470,21 @@ class Pattern extends BasePattern { // Get all inputs with the same name - e.g. radio buttons, checkboxes. inputs = this.siblings(input); } - for (const it of inputs) { + for (const _input of inputs) { if (clear_state) { - this.set_error({ input: it, msg: "", skip_event: true }); + this.set_error({ input: _input, msg: "", skip_event: true }); } - const error_node = it[KEY_ERROR_EL]; - it[KEY_ERROR_EL] = null; + const error_node = _input[KEY_ERROR_EL]; + _input[KEY_ERROR_EL] = null; error_node?.remove(); } // disable selector if (this.form.checkValidity()) { - for (const it of this.disableable) { - if (it.disabled) { - it.removeAttribute("disabled"); - it.classList.remove("disabled"); + for (const _input of this.disableables) { + if (_input.disabled) { + _input.removeAttribute("disabled"); + _input.classList.remove("disabled"); } } } @@ -506,7 +506,7 @@ class Pattern extends BasePattern { // Do not set a error message for a input group like radio buttons or // checkboxes where one has already been set. const inputs = this.siblings(input); - if (inputs.length > 1 && inputs.some((it) => !!it[KEY_ERROR_EL])) { + if (inputs.length > 1 && inputs.some((_input) => !!_input[KEY_ERROR_EL])) { // error message for input group already set. return; } @@ -534,15 +534,15 @@ class Pattern extends BasePattern { input[KEY_ERROR_EL] = error_node; let did_disable = false; - for (const it of this.disableable) { + for (const _input of this.disableables) { // Disable for melements if they are not already disabled and which // do not have set the `formnovalidate` attribute, e.g. // ``. - if (!it.disabled && !it.formNoValidate) { + if (!_input.disabled && !_input.formNoValidate) { did_disable = true; - it.setAttribute("disabled", "disabled"); - it.classList.add("disabled"); - logger.debug("Disable element", it); + _input.setAttribute("disabled", "disabled"); + _input.classList.add("disabled"); + logger.debug("Disable element", _input); } } From f722ceca15b90e5b18b51fa1600cd0943b0ced36 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 15:47:44 +0100 Subject: [PATCH 17/27] maint(docs): Add ADR 0006 on groups for min-values and max-values in pat-validation. Assisted-by: Claude Opus 5.5 --- ...at-validation-groups-for-min-max-values.md | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 docs/adr/0006-pat-validation-groups-for-min-max-values.md diff --git a/docs/adr/0006-pat-validation-groups-for-min-max-values.md b/docs/adr/0006-pat-validation-groups-for-min-max-values.md new file mode 100644 index 000000000..0b640a5bb --- /dev/null +++ b/docs/adr/0006-pat-validation-groups-for-min-max-values.md @@ -0,0 +1,67 @@ +# 0006 pat-validation: Groups for min-values and max-values + +Status: Accepted (2026-11-27) + +## Context + +We need to validate a minimum and maximum number of checked checkboxes, e.g. +"select at least one and at most three options". There is no native HTML +constraint for that. The `required` attribute only works for radio buttons as +a group. + +pat-validation validates single inputs. For a minimum or maximum number of +values we need a group of inputs: + +- to count the checked, selected or filled-out values, +- to set and clear the validation state on all members of the group, +- to place one error message for the whole group. + +The first implementation defined the group by the inputs with the same name. +This does not cover groups of differently named checkboxes, e.g. +`newsletter`, `updates` and `events`. + +The options can be defined on a wrapper element like a fieldset and are +inherited by the inputs. But the parser merges inherited options and loses the +information which element defined them, so the wrapper cannot be found via +the parsed options of an input. + +## Decision + +The `min-values` and `max-values` options define the group: + +- The group root is the closest element - starting at the input and going up + to and including the form - which itself defines `min-values` or + `max-values`. Only the options defined directly on an element are taken into + account (the parser is called without inheritance). +- If the input itself defines the options, the group consists of all inputs + with the same name. +- If a wrapper element defines the options, the group consists of all inputs + of the form within that wrapper, regardless of their names. +- If the form defines the options, the group consists of all inputs of the + form, including inputs outside the form element. +- Without such a definition, the group consists of all inputs with the same + name (e.g. radio buttons and checkboxes). + +All members of a group share the same validation state. The error message is +placed after the last member of the group or after its label, if the input is +wrapped in a label. + +Checkboxes and radio buttons count if checked, selects count their selected +options and all other inputs count if they have a value. + +We did not introduce a separate option or pattern to define groups, so that +the group is defined where the constraint is defined. + +## Consequences + +- Groups of differently named inputs are supported by putting the options on + a wrapper element. +- A wrapper element should only contain the inputs of the group. Every check + of a group member re-evaluates and clears the state of the whole group, also + for unrelated inputs within the wrapper. +- `min-values` and `max-values` should be defined on the same element. The + values are read from the input with inheritance, so options split across + nested elements would be combined while the group is defined by the inner + element. +- Finding the group root parses the ancestors of an input each time the group + is needed. This is acceptable for typical form sizes. From 27843a98a5c5915d01c3816434b7f952b91da6e8 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Thu, 26 Nov 2026 02:42:24 +0100 Subject: [PATCH 18/27] feat(pat-validation): Support min-values and max-values on wrapper elements 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 --- src/pat/validation/documentation.md | 31 ++++- src/pat/validation/index.html | 12 ++ src/pat/validation/validation.js | 36 +++++- src/pat/validation/validation.test.js | 160 ++++++++++++++++++++++++++ 4 files changed, 235 insertions(+), 4 deletions(-) diff --git a/src/pat/validation/documentation.md b/src/pat/validation/documentation.md index 6195d7f35..7961ff018 100644 --- a/src/pat/validation/documentation.md +++ b/src/pat/validation/documentation.md @@ -89,7 +89,7 @@ In addition both the input element and its label will get an `warning` class. ``` -Checkboxes and radio buttons are treated differently: The error message is always set after the last element of the inputs with the same name. If that input is wrapped in a label, the error message is set after the label. +Checkboxes and radio buttons are treated differently: The error message is always set after the last element of the inputs with the same name - or of the group of inputs, see [Minimum and maximum number of values](#minimum-and-maximum-number-of-values). If that input is wrapped in a label, the error message is set after the label. ```html
@@ -111,6 +111,31 @@ ValidationPattern.prototype.error_template = (message) => ``` +### Minimum and maximum number of values + +With `min-values` and `max-values` you can define how many inputs of a group must be checked, selected or filled out. +This is most useful for checkboxes, but also works for text inputs, selects and other form elements. + +A group is defined either: + +- by the inputs with the same name, if the options are defined on the input itself, or +- by all inputs within a wrapper element, if the options are defined on a wrapper element like a fieldset. + In this case the inputs do not need to share the same name. + +```html +
+ + + +
+``` + +All inputs of a group share the same validation state and the error message is placed after the last input of the group. +Therefore a wrapper element should only contain the inputs of the group. +If `min-values` or `max-values` is defined on the form itself, all inputs of the form form one group. +Define `min-values` and `max-values` on the same element. + + ### Form elements outside the form Input elements outside of form elements are fully supported. @@ -158,6 +183,6 @@ There is no need to re-initialize the pattern or to dispatch a special event. | equality | Field-specific extra rule. The name of another input this input should equal to (useful for password confirmation). | | String | | not-after | Field-specific extra rule. A lower time limit restriction for date and datetime fields. | | CSS Selector or a ISO8601 date string. | | not-before | Field-specific extra rule. An upper time limit restriction for date and datetime fields. | | CSS Selector or a ISO8601 date 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) | +| min-values | Minimum number of checked, selected or filled out form elements of a group (same name or wrapper element). | null | Integer (or null) | +| max-values | Maximum number of checked, selected or filled out form elements of a group (same name or wrapper element). | null | Integer (or null) | | delay | Time in milliseconds before validation starts to avoid validating while typing. | 100 | Integer | diff --git a/src/pat/validation/index.html b/src/pat/validation/index.html index 8dd852e7f..d69bb743c 100644 --- a/src/pat/validation/index.html +++ b/src/pat/validation/index.html @@ -389,6 +389,18 @@

Demo with max-values / min-values support

+ +
+ Demo with a group of differently named checkboxes (min 1, max 2). + + + +
diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index 01774fd4b..f2c6a09e8 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -138,8 +138,42 @@ class Pattern extends BasePattern { ); } + group_root(input) { + // Return the closest ancestor element of an input - up to and + // including the form - which itself defines `min-values` or + // `max-values`. All inputs within this element form a group. + // Return null if there is no such element or if the input itself + // defines these options. + for (let el = input; el; el = el.parentElement) { + if (el.hasAttribute(parser.attribute)) { + // Parse only the options defined on this element. + const options = parser.parse(el, {}, false, false); + if ( + (options.minValues ?? null) !== null || + (options.maxValues ?? null) !== null + ) { + return el === input ? null : el; + } + } + if (el === this.form) { + break; + } + } + return null; + } + siblings(input) { - // Get all siblings of an input with the same name. + // Get all inputs which belong to the same group as the given input. + // If a wrapper element defines `min-values` or `max-values`, all + // inputs within that wrapper form a group. Otherwise all inputs with + // the same name form a group. + const group_root = this.group_root(input); + if (group_root === this.form) { + return this.inputs; + } + if (group_root) { + return this.inputs.filter((_input) => group_root.contains(_input)); + } return this.inputs.filter((_input) => _input.name === input.name); } diff --git a/src/pat/validation/validation.test.js b/src/pat/validation/validation.test.js index 89c3efe95..ddcb6d28b 100644 --- a/src/pat/validation/validation.test.js +++ b/src/pat/validation/validation.test.js @@ -2340,6 +2340,166 @@ describe("pat-validation", function () { expect(check1.matches(":invalid")).toBe(false); expect(form.querySelectorAll("em.warning").length).toBe(0); }); + + it("10.4 - validates a group of differently named inputs defined by a wrapper", async function () { + document.body.innerHTML = ` +
+
+ + + +
+ +
+ `; + + const form = document.querySelector("form"); + const fieldset = form.querySelector("fieldset"); + const c1 = form.querySelector("#c1"); + const c2 = form.querySelector("#c2"); + const c3 = form.querySelector("#c3"); + const other = form.querySelector("#other"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + // Nothing checked. + c1.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(c1.matches(":invalid")).toBe(true); + expect(c2.matches(":invalid")).toBe(true); + expect(c3.matches(":invalid")).toBe(true); + // The input outside the group is not affected. + expect(other.matches(":invalid")).toBe(true); // required + expect(fieldset.querySelectorAll("em.warning").length).toBe(1); + expect(fieldset.querySelector("em.warning").textContent).toBe( + "Select at least one" + ); + // The error message is placed after the label of the last input. + expect( + fieldset.querySelector("label:nth-of-type(3) + em.warning") + ).toBeTruthy(); + + // One checked - valid. + c2.checked = true; + c2.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(c1.matches(":invalid")).toBe(false); + expect(c2.matches(":invalid")).toBe(false); + expect(c3.matches(":invalid")).toBe(false); + expect(fieldset.querySelectorAll("em.warning").length).toBe(0); + + // Two checked - valid. + c3.checked = true; + c3.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(c1.matches(":invalid")).toBe(false); + expect(fieldset.querySelectorAll("em.warning").length).toBe(0); + + // Three checked - invalid. + c1.checked = true; + c1.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(c1.matches(":invalid")).toBe(true); + expect(c2.matches(":invalid")).toBe(true); + expect(c3.matches(":invalid")).toBe(true); + expect(fieldset.querySelectorAll("em.warning").length).toBe(1); + expect(fieldset.querySelector("em.warning").textContent).toBe( + "Select at most two" + ); + + // Back to two checked - valid. + c1.checked = false; + c1.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(c1.matches(":invalid")).toBe(false); + expect(c2.matches(":invalid")).toBe(false); + expect(c3.matches(":invalid")).toBe(false); + expect(fieldset.querySelectorAll("em.warning").length).toBe(0); + }); + + it("10.5 - validates a wrapper group on submit", async function () { + document.body.innerHTML = ` +
+
+ + +
+ +
+ `; + + const form = document.querySelector("form"); + const c2 = form.querySelector("#c2"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + const submit_event = events.submit_event(); + form.dispatchEvent(submit_event); + await utils.timeout(1); // wait a tick for async to settle. + + expect(submit_event.defaultPrevented).toBe(true); + expect(form.querySelectorAll("em.warning").length).toBe(1); + expect(form.querySelector("#c2 + em.warning")).toBeTruthy(); + expect(form.querySelector("button").disabled).toBe(true); + + c2.checked = true; + c2.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(form.querySelectorAll("em.warning").length).toBe(0); + expect(form.querySelector("button").disabled).toBe(false); + }); + + it("10.6 - groups by name if the input itself defines min/max values", async function () { + document.body.innerHTML = ` +
+
+ + + +
+
+ `; + + const form = document.querySelector("form"); + const b1 = form.querySelector("#b1"); + const b2 = form.querySelector("#b2"); + const a1 = form.querySelector("#a1"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + // The b group is checked by name: 1 of b checked - valid. + b1.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(b1.matches(":invalid")).toBe(false); + expect(b2.matches(":invalid")).toBe(false); + expect(form.querySelectorAll("em.warning").length).toBe(0); + + // The fieldset group: a1 and b1 checked - max-values 1 exceeded. + a1.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(a1.matches(":invalid")).toBe(true); + expect(form.querySelectorAll("em.warning").length).toBe(1); + }); }); }); From 839610364d195845ef93f19753bad0205494eef7 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Sat, 28 Nov 2026 00:38:18 +0100 Subject: [PATCH 19/27] fix(pat-validation): Remove the wrapper groups for min-values and max-values. This reverts commits 27843a98a and f722ceca1 (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 --- ...at-validation-groups-for-min-max-values.md | 67 -------- src/pat/validation/documentation.md | 31 +--- src/pat/validation/index.html | 12 -- src/pat/validation/validation.js | 36 +--- src/pat/validation/validation.test.js | 162 ++++-------------- 5 files changed, 37 insertions(+), 271 deletions(-) delete mode 100644 docs/adr/0006-pat-validation-groups-for-min-max-values.md diff --git a/docs/adr/0006-pat-validation-groups-for-min-max-values.md b/docs/adr/0006-pat-validation-groups-for-min-max-values.md deleted file mode 100644 index 0b640a5bb..000000000 --- a/docs/adr/0006-pat-validation-groups-for-min-max-values.md +++ /dev/null @@ -1,67 +0,0 @@ -# 0006 pat-validation: Groups for min-values and max-values - -Status: Accepted (2026-11-27) - -## Context - -We need to validate a minimum and maximum number of checked checkboxes, e.g. -"select at least one and at most three options". There is no native HTML -constraint for that. The `required` attribute only works for radio buttons as -a group. - -pat-validation validates single inputs. For a minimum or maximum number of -values we need a group of inputs: - -- to count the checked, selected or filled-out values, -- to set and clear the validation state on all members of the group, -- to place one error message for the whole group. - -The first implementation defined the group by the inputs with the same name. -This does not cover groups of differently named checkboxes, e.g. -`newsletter`, `updates` and `events`. - -The options can be defined on a wrapper element like a fieldset and are -inherited by the inputs. But the parser merges inherited options and loses the -information which element defined them, so the wrapper cannot be found via -the parsed options of an input. - -## Decision - -The `min-values` and `max-values` options define the group: - -- The group root is the closest element - starting at the input and going up - to and including the form - which itself defines `min-values` or - `max-values`. Only the options defined directly on an element are taken into - account (the parser is called without inheritance). -- If the input itself defines the options, the group consists of all inputs - with the same name. -- If a wrapper element defines the options, the group consists of all inputs - of the form within that wrapper, regardless of their names. -- If the form defines the options, the group consists of all inputs of the - form, including inputs outside the form element. -- Without such a definition, the group consists of all inputs with the same - name (e.g. radio buttons and checkboxes). - -All members of a group share the same validation state. The error message is -placed after the last member of the group or after its label, if the input is -wrapped in a label. - -Checkboxes and radio buttons count if checked, selects count their selected -options and all other inputs count if they have a value. - -We did not introduce a separate option or pattern to define groups, so that -the group is defined where the constraint is defined. - -## Consequences - -- Groups of differently named inputs are supported by putting the options on - a wrapper element. -- A wrapper element should only contain the inputs of the group. Every check - of a group member re-evaluates and clears the state of the whole group, also - for unrelated inputs within the wrapper. -- `min-values` and `max-values` should be defined on the same element. The - values are read from the input with inheritance, so options split across - nested elements would be combined while the group is defined by the inner - element. -- Finding the group root parses the ancestors of an input each time the group - is needed. This is acceptable for typical form sizes. diff --git a/src/pat/validation/documentation.md b/src/pat/validation/documentation.md index 7961ff018..6195d7f35 100644 --- a/src/pat/validation/documentation.md +++ b/src/pat/validation/documentation.md @@ -89,7 +89,7 @@ In addition both the input element and its label will get an `warning` class. ``` -Checkboxes and radio buttons are treated differently: The error message is always set after the last element of the inputs with the same name - or of the group of inputs, see [Minimum and maximum number of values](#minimum-and-maximum-number-of-values). If that input is wrapped in a label, the error message is set after the label. +Checkboxes and radio buttons are treated differently: The error message is always set after the last element of the inputs with the same name. If that input is wrapped in a label, the error message is set after the label. ```html
@@ -111,31 +111,6 @@ ValidationPattern.prototype.error_template = (message) => ``` -### Minimum and maximum number of values - -With `min-values` and `max-values` you can define how many inputs of a group must be checked, selected or filled out. -This is most useful for checkboxes, but also works for text inputs, selects and other form elements. - -A group is defined either: - -- by the inputs with the same name, if the options are defined on the input itself, or -- by all inputs within a wrapper element, if the options are defined on a wrapper element like a fieldset. - In this case the inputs do not need to share the same name. - -```html -
- - - -
-``` - -All inputs of a group share the same validation state and the error message is placed after the last input of the group. -Therefore a wrapper element should only contain the inputs of the group. -If `min-values` or `max-values` is defined on the form itself, all inputs of the form form one group. -Define `min-values` and `max-values` on the same element. - - ### Form elements outside the form Input elements outside of form elements are fully supported. @@ -183,6 +158,6 @@ There is no need to re-initialize the pattern or to dispatch a special event. | equality | Field-specific extra rule. The name of another input this input should equal to (useful for password confirmation). | | String | | not-after | Field-specific extra rule. A lower time limit restriction for date and datetime fields. | | CSS Selector or a ISO8601 date string. | | not-before | Field-specific extra rule. An upper time limit restriction for date and datetime fields. | | CSS Selector or a ISO8601 date string. | -| min-values | Minimum number of checked, selected or filled out form elements of a group (same name or wrapper element). | null | Integer (or null) | -| max-values | Maximum number of checked, selected or filled out form elements of a group (same name or wrapper element). | null | Integer (or null) | +| 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) | | delay | Time in milliseconds before validation starts to avoid validating while typing. | 100 | Integer | diff --git a/src/pat/validation/index.html b/src/pat/validation/index.html index d69bb743c..8dd852e7f 100644 --- a/src/pat/validation/index.html +++ b/src/pat/validation/index.html @@ -389,18 +389,6 @@

Demo with max-values / min-values support

- -
- Demo with a group of differently named checkboxes (min 1, max 2). - - - -
diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index f2c6a09e8..01774fd4b 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -138,42 +138,8 @@ class Pattern extends BasePattern { ); } - group_root(input) { - // Return the closest ancestor element of an input - up to and - // including the form - which itself defines `min-values` or - // `max-values`. All inputs within this element form a group. - // Return null if there is no such element or if the input itself - // defines these options. - for (let el = input; el; el = el.parentElement) { - if (el.hasAttribute(parser.attribute)) { - // Parse only the options defined on this element. - const options = parser.parse(el, {}, false, false); - if ( - (options.minValues ?? null) !== null || - (options.maxValues ?? null) !== null - ) { - return el === input ? null : el; - } - } - if (el === this.form) { - break; - } - } - return null; - } - siblings(input) { - // Get all inputs which belong to the same group as the given input. - // If a wrapper element defines `min-values` or `max-values`, all - // inputs within that wrapper form a group. Otherwise all inputs with - // the same name form a group. - const group_root = this.group_root(input); - if (group_root === this.form) { - return this.inputs; - } - if (group_root) { - return this.inputs.filter((_input) => group_root.contains(_input)); - } + // Get all siblings of an input with the same name. return this.inputs.filter((_input) => _input.name === input.name); } diff --git a/src/pat/validation/validation.test.js b/src/pat/validation/validation.test.js index ddcb6d28b..c626ec3c1 100644 --- a/src/pat/validation/validation.test.js +++ b/src/pat/validation/validation.test.js @@ -2340,165 +2340,69 @@ describe("pat-validation", function () { expect(check1.matches(":invalid")).toBe(false); expect(form.querySelectorAll("em.warning").length).toBe(0); }); + }); - it("10.4 - validates a group of differently named inputs defined by a wrapper", async function () { + describe("11 - min/max values do not hide errors of other inputs", function () { + it("11.1 - keeps the error of a required input in a fieldset with min-values", async function () { document.body.innerHTML = `
-
- - - +
+ +
- + `; - - const form = document.querySelector("form"); - const fieldset = form.querySelector("fieldset"); - const c1 = form.querySelector("#c1"); - const c2 = form.querySelector("#c2"); - const c3 = form.querySelector("#c3"); - const other = form.querySelector("#other"); - - const instance = new Pattern(form); + const el = document.querySelector(".pat-validation"); + const instance = new Pattern(el); await events.await_pattern_init(instance); - // Nothing checked. - c1.dispatchEvent(events.change_event()); - await utils.timeout(1); // wait a tick for async to settle. - - expect(c1.matches(":invalid")).toBe(true); - expect(c2.matches(":invalid")).toBe(true); - expect(c3.matches(":invalid")).toBe(true); - // The input outside the group is not affected. - expect(other.matches(":invalid")).toBe(true); // required - expect(fieldset.querySelectorAll("em.warning").length).toBe(1); - expect(fieldset.querySelector("em.warning").textContent).toBe( - "Select at least one" - ); - // The error message is placed after the label of the last input. - expect( - fieldset.querySelector("label:nth-of-type(3) + em.warning") - ).toBeTruthy(); - - // One checked - valid. - c2.checked = true; - c2.dispatchEvent(events.change_event()); - await utils.timeout(1); // wait a tick for async to settle. - - expect(c1.matches(":invalid")).toBe(false); - expect(c2.matches(":invalid")).toBe(false); - expect(c3.matches(":invalid")).toBe(false); - expect(fieldset.querySelectorAll("em.warning").length).toBe(0); - - // Two checked - valid. - c3.checked = true; - c3.dispatchEvent(events.change_event()); - await utils.timeout(1); // wait a tick for async to settle. - - expect(c1.matches(":invalid")).toBe(false); - expect(fieldset.querySelectorAll("em.warning").length).toBe(0); - - // Three checked - invalid. - c1.checked = true; - c1.dispatchEvent(events.change_event()); - await utils.timeout(1); // wait a tick for async to settle. - - expect(c1.matches(":invalid")).toBe(true); - expect(c2.matches(":invalid")).toBe(true); - expect(c3.matches(":invalid")).toBe(true); - expect(fieldset.querySelectorAll("em.warning").length).toBe(1); - expect(fieldset.querySelector("em.warning").textContent).toBe( - "Select at most two" - ); - - // Back to two checked - valid. - c1.checked = false; - c1.dispatchEvent(events.change_event()); + el.dispatchEvent(events.submit_event()); await utils.timeout(1); // wait a tick for async to settle. - expect(c1.matches(":invalid")).toBe(false); - expect(c2.matches(":invalid")).toBe(false); - expect(c3.matches(":invalid")).toBe(false); - expect(fieldset.querySelectorAll("em.warning").length).toBe(0); + expect(el.querySelector("[name=name]").validity.valid).toBe(false); + expect(el.querySelectorAll("em.warning").length).toBe(1); }); - it("10.5 - validates a wrapper group on submit", async function () { + it("11.2 - keeps the error of a required input with min-values on the form", async function () { document.body.innerHTML = ` -
-
- - -
- + + + +
`; - - const form = document.querySelector("form"); - const c2 = form.querySelector("#c2"); - - const instance = new Pattern(form); + const el = document.querySelector(".pat-validation"); + const instance = new Pattern(el); await events.await_pattern_init(instance); - const submit_event = events.submit_event(); - form.dispatchEvent(submit_event); - await utils.timeout(1); // wait a tick for async to settle. - - expect(submit_event.defaultPrevented).toBe(true); - expect(form.querySelectorAll("em.warning").length).toBe(1); - expect(form.querySelector("#c2 + em.warning")).toBeTruthy(); - expect(form.querySelector("button").disabled).toBe(true); - - c2.checked = true; - c2.dispatchEvent(events.change_event()); + el.dispatchEvent(events.submit_event()); await utils.timeout(1); // wait a tick for async to settle. - expect(form.querySelectorAll("em.warning").length).toBe(0); - expect(form.querySelector("button").disabled).toBe(false); + expect(el.querySelectorAll("em.warning").length).toBe(1); }); - it("10.6 - groups by name if the input itself defines min/max values", async function () { + it("11.3 - keeps the equality error of an input in a fieldset with min-values", async function () { document.body.innerHTML = `
-
- - - + +
+ +
+ `; - - const form = document.querySelector("form"); - const b1 = form.querySelector("#b1"); - const b2 = form.querySelector("#b2"); - const a1 = form.querySelector("#a1"); - - const instance = new Pattern(form); + const el = document.querySelector(".pat-validation"); + const instance = new Pattern(el); await events.await_pattern_init(instance); - // The b group is checked by name: 1 of b checked - valid. - b1.dispatchEvent(events.change_event()); - await utils.timeout(1); // wait a tick for async to settle. - - expect(b1.matches(":invalid")).toBe(false); - expect(b2.matches(":invalid")).toBe(false); - expect(form.querySelectorAll("em.warning").length).toBe(0); - - // The fieldset group: a1 and b1 checked - max-values 1 exceeded. - a1.dispatchEvent(events.change_event()); + el.dispatchEvent(events.submit_event()); await utils.timeout(1); // wait a tick for async to settle. - expect(a1.matches(":invalid")).toBe(true); - expect(form.querySelectorAll("em.warning").length).toBe(1); + expect(el.querySelector("[name=confirm]").validity.valid).toBe(false); + expect(el.querySelectorAll("em.warning").length).toBe(1); }); }); From 2f22fe4bff5b98f644c373145f93c4fc380b0644 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Sat, 28 Nov 2026 00:38:26 +0100 Subject: [PATCH 20/27] fix(pat-validation): Speed up the lookup of inputs with the same name. 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 --- src/pat/validation/validation.js | 24 +++++++++-- src/pat/validation/validation.test.js | 59 +++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 3 deletions(-) diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index 01774fd4b..3cd537053 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -139,8 +139,22 @@ class Pattern extends BasePattern { } siblings(input) { - // Get all siblings of an input with the same name. - return this.inputs.filter((_input) => _input.name === input.name); + // Get all siblings of an input with the same name, including the + // input itself. + if (!input.name) { + return [input]; + } + // Use the form's named lookup instead of filtering all form + // elements. It returns the elements with this name or id - also + // those outside the form which are associated via the ``form`` + // attribute - as a single element or a ``RadioNodeList``. + const named = this.form.elements.namedItem(input.name); + const candidates = named instanceof Element ? [named] : [...(named || [])]; + return candidates.filter( + (_input) => + _input.name === input.name && + _input.matches("input[name], select[name], textarea[name]"), + ); } async validate_all(event) { @@ -472,7 +486,11 @@ class Pattern extends BasePattern { } for (const _input of inputs) { if (clear_state) { - this.set_error({ input: _input, msg: "", skip_event: true }); + // Clear the error state directly instead of via + // ``set_error``, which would get the siblings of each sibling + // again. + _input.setCustomValidity(""); + _input[KEY_ERROR_MSG] = ""; } const error_node = _input[KEY_ERROR_EL]; _input[KEY_ERROR_EL] = null; diff --git a/src/pat/validation/validation.test.js b/src/pat/validation/validation.test.js index c626ec3c1..41a79d0cf 100644 --- a/src/pat/validation/validation.test.js +++ b/src/pat/validation/validation.test.js @@ -2406,4 +2406,63 @@ describe("pat-validation", function () { }); }); + describe("12 - siblings", function () { + it("12.1 - returns the inputs with the same name, also outside the form", async function () { + document.body.innerHTML = ` +
+ + +
+ +
+ +
+ + + `; + const el = document.querySelector(".pat-validation"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + // Not the input with the id "a", not the button with the name "a" + // and not the input which is not associated with the form. + const siblings = instance.siblings(document.querySelector("#a1")); + expect(siblings.map((it) => it.id)).toEqual(["a1", "a2", "a3"]); + }); + + it("12.2 - returns a single input or select", async function () { + document.body.innerHTML = ` +
+ + +
+ `; + const el = document.querySelector(".pat-validation"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + const input = document.querySelector("#a"); + const select = document.querySelector("#s"); + expect(instance.siblings(input)).toEqual([input]); + expect(instance.siblings(select)).toEqual([select]); + }); + + it("12.3 - returns only the input itself if it has no name", async function () { + document.body.innerHTML = ` +
+ + +
+ `; + const el = document.querySelector(".pat-validation"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + const input = document.querySelector("#a"); + expect(instance.siblings(input)).toEqual([input]); + }); + }); }); From d9e9cdc19cde6ed597f5c1a10656831f8f93cb81 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Sat, 28 Nov 2026 02:19:31 +0100 Subject: [PATCH 21/27] fix(pat-validation): Do not count hidden inputs, disabled inputs and 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 --- src/pat/validation/documentation.md | 19 ++++++++++ src/pat/validation/validation.js | 12 +++++++ src/pat/validation/validation.test.js | 50 +++++++++++++++++++++++++++ 3 files changed, 81 insertions(+) diff --git a/src/pat/validation/documentation.md b/src/pat/validation/documentation.md index 6195d7f35..cde2aed9a 100644 --- a/src/pat/validation/documentation.md +++ b/src/pat/validation/documentation.md @@ -111,6 +111,25 @@ ValidationPattern.prototype.error_template = (message) => ``` +### Minimum and maximum number of values + +With `min-values` and `max-values` you can define how many inputs with the same name must be checked, selected or filled out. +This is most useful for checkboxes, but also works for text inputs, selects and other form elements. + +Checkboxes and radio buttons count if they are checked, selects count their selected options and all other inputs count if they have a value. +Hidden inputs, disabled inputs and buttons are not counted. +This allows a hidden input with the same name to submit a default value if no checkbox is checked. + +```html +
+ + + + +
+``` + + ### Form elements outside the form Input elements outside of form elements are fully supported. diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index 3cd537053..d63a8005a 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -327,6 +327,18 @@ class Pattern extends BasePattern { let number_values = 0; for (const _input of this.siblings(input)) { + // Do not count inputs which the user cannot change - + // hidden and disabled inputs, e.g. a hidden input which + // submits a default value - and buttons. + if ( + _input.disabled || + ["hidden", "submit", "button", "reset", "image"].includes( + _input.type, + ) + ) { + continue; + } + // Check if checkboxes or radios are checked ... if (_input.type === "checkbox" || _input.type === "radio") { if (_input.checked) { diff --git a/src/pat/validation/validation.test.js b/src/pat/validation/validation.test.js index 41a79d0cf..cc55cd36d 100644 --- a/src/pat/validation/validation.test.js +++ b/src/pat/validation/validation.test.js @@ -2340,6 +2340,56 @@ describe("pat-validation", function () { expect(check1.matches(":invalid")).toBe(false); expect(form.querySelectorAll("em.warning").length).toBe(0); }); + + it("10.4 - does not count hidden inputs, disabled inputs and buttons", async function () { + // A hidden input with the same name as the checkboxes is a common + // pattern to submit a default value if no checkbox is checked. + document.body.innerHTML = ` +
+
+ + + + + + + +
+
+ `; + + const form = document.querySelector("form"); + const c1 = form.querySelector("#c1"); + + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + // No enabled checkbox is checked. + const submit_event = events.submit_event(); + form.dispatchEvent(submit_event); + await utils.timeout(1); // wait a tick for async to settle. + + expect(submit_event.defaultPrevented).toBe(true); + expect(c1.matches(":invalid")).toBe(true); + expect(form.querySelectorAll("em.warning").length).toBe(1); + expect(form.querySelector("em.warning").textContent).toBe("too few"); + + // One enabled checkbox is checked. The disabled checked one does + // not count towards max-values. + c1.checked = true; + c1.dispatchEvent(events.change_event()); + await utils.timeout(1); // wait a tick for async to settle. + + expect(c1.matches(":invalid")).toBe(false); + expect(form.querySelectorAll("em.warning").length).toBe(0); + }); }); describe("11 - min/max values do not hide errors of other inputs", function () { From 3a72be6e47c9f80e1a2748776431e695c2ee2cc4 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Sat, 28 Nov 2026 02:46:07 +0100 Subject: [PATCH 22/27] pat-validation autoformat. --- src/pat/validation/index.html | 291 +++++++++++++++++----------------- 1 file changed, 149 insertions(+), 142 deletions(-) diff --git a/src/pat/validation/index.html b/src/pat/validation/index.html index 8dd852e7f..59f8dcc75 100644 --- a/src/pat/validation/index.html +++ b/src/pat/validation/index.html @@ -2,8 +2,10 @@ Form validation - - + + - - -

Demo with max-values / min-values support

- - -
- -
- - -
-
- - - - From 2dd12e2e483790a7fda8a8c08110b98c0f60eb63 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Sat, 28 Nov 2026 03:13:26 +0100 Subject: [PATCH 27/27] =?UTF-8?q?pat-validation:=20tmp.md=20Remove=20note?= =?UTF-8?q?=20to=20Dani=C3=ABl.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/pat/validation/tmp.md | 14 -------------- 1 file changed, 14 deletions(-) delete mode 100644 src/pat/validation/tmp.md diff --git a/src/pat/validation/tmp.md b/src/pat/validation/tmp.md deleted file mode 100644 index 714b90745..000000000 --- a/src/pat/validation/tmp.md +++ /dev/null @@ -1,14 +0,0 @@ -Hi Daniƫl, - -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 to support that. - -Please see this implementation as a draft to discuss about. - -These parameters were added: - -- min-values: The minimum number of values to be checked, selected of filled-out.