Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
432c417
pat-validation: Autoformat.
thet Nov 26, 2026
0a6c36b
maint(core dom): Add test to prove that jsDOM supports input elements…
thet May 13, 2025
f3f782d
feat(core events): Add focusin and focusout event factories.
thet May 13, 2025
c8b3ed1
maint(pat-validation): Minor code cleanup.
thet May 13, 2025
27853c5
tech(pat-validation): Use this.form instead of this.el for clarity.
thet May 13, 2025
b3f09d6
tech(pat-validation): Create a validate_all API method.
thet May 12, 2025
2feee46
fix(pat-validation): When removing the error, also clear the error st…
thet May 12, 2025
b3ec19f
feat(pat-validation): Support form elements outside the form.
thet May 13, 2025
0e65e5b
feat(pat-validation): Support definition of minimum or maximum number…
thet May 13, 2025
90df036
fix(pat-validation): Put error messages always at the end of a group …
thet May 13, 2025
b80ac3e
maint(docs): Add ADR 0005 on event delegation with focusout in pat-va…
thet Nov 27, 2026
42f69f1
feat(pat-validation): Support dynamic forms.
thet Nov 26, 2026
9a62ad4
fixup! feat(pat-validation): Support dynamic forms.
thet Nov 27, 2026
bf844bb
fix(pat-validation): Support the combination of multiple custom valid…
thet Nov 26, 2026
4de3525
tech(pat-validation): Generalize the method to retrieve siblings.
thet May 14, 2025
f451903
tech(pat-validation): Cleanup - better variable names.
thet May 19, 2025
f722cec
maint(docs): Add ADR 0006 on groups for min-values and max-values in …
thet Nov 27, 2026
27843a9
feat(pat-validation): Support min-values and max-values on wrapper el…
thet Nov 26, 2026
8396103
fix(pat-validation): Remove the wrapper groups for min-values and max…
thet Nov 27, 2026
2f22fe4
fix(pat-validation): Speed up the lookup of inputs with the same name.
thet Nov 27, 2026
d9e9cdc
fix(pat-validation): Do not count hidden inputs, disabled inputs and …
thet Nov 28, 2026
3a72be6
pat-validation autoformat.
thet Nov 28, 2026
1c32ba9
maint(pat-validation): index.html - Add input outside form for min-va…
thet Nov 28, 2026
347f0d8
maint(pat-validation): index.html - More labels for min-values/max-va…
thet Nov 28, 2026
3d92221
pat-validation: maxmin.html Use blur->focusout event.
thet Nov 28, 2026
b0c6f49
pat-validation: maxmin.html Remove obsolete demo file.
thet Nov 28, 2026
2dd12e2
pat-validation: tmp.md Remove note to Daniël.
thet Nov 28, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions docs/adr/0005-pat-validation-event-delegation-with-focusout.md
Original file line number Diff line number Diff line change
@@ -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.
18 changes: 18 additions & 0 deletions src/core/dom.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,24 @@ describe("core.dom tests", () => {
jest.restoreAllMocks();
});

describe("jsDOM tests", () => {
it("jsDOM supports input elements outside forms.", () => {
document.body.innerHTML = `
<input name="outside" form="a_form"/>
<form id="a_form">
<input name="inside"/>
</form>
`;

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;
Expand Down
18 changes: 17 additions & 1 deletion src/core/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
18 changes: 18 additions & 0 deletions src/core/events.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
6 changes: 3 additions & 3 deletions src/pat/auto-suggest/auto-suggest.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
6 changes: 3 additions & 3 deletions src/pat/date-picker/date-picker.js
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
},
};
Expand Down
4 changes: 3 additions & 1 deletion src/pat/datetime-picker/datetime-picker.js
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
});
}
Expand Down
25 changes: 25 additions & 0 deletions src/pat/datetime-picker/datetime-picker.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = `
<input type="datetime-local" class="pat-datetime-picker" name="dt"/>
<button id="outside">outside</button>
`;
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);
});
});
50 changes: 48 additions & 2 deletions src/pat/validation/documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -88,10 +89,10 @@ In addition both the input element and its label will get an `warning` class.
</label>
```

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
<fieldset class="checklist radio">
<fieldset>
<label><input type="radio" name="radio" /> Strawberry</label>
<label><input type="radio" name="radio" /> Banana</label>
<label><input type="radio" name="radio" /> Raspberry</label>
Expand All @@ -109,6 +110,47 @@ ValidationPattern.prototype.error_template = (message) =>
`<em class="invalid-feedback">${message}</em>`;
```


### 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
<fieldset data-pat-validation="min-values: 1; max-values: 2">
<input type="hidden" name="topics" value="" />
<label><input type="checkbox" name="topics" value="news" /> News</label>
<label><input type="checkbox" name="topics" value="updates" /> Updates</label>
<label><input type="checkbox" name="topics" value="events" /> Events</label>
</fieldset>
```


### Form elements outside the form

Input elements outside of form elements are fully supported.
pat-validation can handle structures like these:

```html
<input name="outside" form="myform" required>
<form id="myform">
</form>
<button form="myform">submit</button>
```

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
Expand All @@ -130,7 +172,11 @@ ValidationPattern.prototype.error_template = (message) =>
| 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 |
Loading