Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
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 @@ -172,7 +172,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 @@ -231,6 +231,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 @@ -293,6 +307,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 @@ -529,6 +529,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);
});
});
56 changes: 54 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 - 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
<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,53 @@ 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 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
<fieldset data-pat-validation="min-values: 1; max-values: 2">
<label><input type="checkbox" name="newsletter" /> Newsletter</label>
<label><input type="checkbox" name="updates" /> Product updates</label>
<label><input type="checkbox" name="events" /> Event invitations</label>
</fieldset>
```

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.
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 +178,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 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 |
Loading