Skip to content

Commit a504508

Browse files
authored
feat: add calciteInvalid event for form validation (#9211)
**Related Issue:** #9210 ## Summary Add a `calciteInvalid` event (like [`invalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event)), which fires if a component's validation constraints aren't met during form submission. This will make it easier to set custom validation messages on form submission. Once #9210 lands, I'll update the new validation demo it adds to use `calciteInvalid`.
1 parent becb2e3 commit a504508

File tree

2 files changed

+9
-0
lines changed

2 files changed

+9
-0
lines changed

packages/calcite-components/src/tests/commonTests/formAssociated.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,13 +167,19 @@ export function formAssociated(
167167

168168
const submitButton = await page.find("#submitButton");
169169
const spyEvent = await page.spyOnEvent(getClearValidationEventName(tag));
170+
const spyInvalidEvent = await page.spyOnEvent("calciteInvalid");
170171

171172
const requiredValidationMessage =
172173
options?.inputType === "radio" ? "Please select one of these options." : "Please fill out this field.";
173174

174175
await assertPreventsFormSubmission(page, component, submitButton, requiredValidationMessage);
176+
expect(spyInvalidEvent).toHaveReceivedEventTimes(1);
177+
175178
await assertClearsValidationOnValueChange(page, component, options, spyEvent, tag);
179+
expect(spyInvalidEvent).toHaveReceivedEventTimes(1);
180+
176181
await assertUserMessageNotOverridden(page, component, submitButton);
182+
expect(spyInvalidEvent).toHaveReceivedEventTimes(2);
177183
}
178184

179185
function ensureName(html: string, componentTag: string): string {

packages/calcite-components/src/utils/form.tsx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,9 @@ function invalidHandler(event: Event) {
260260
// prevent the browser from showing the native validation popover
261261
event?.preventDefault();
262262

263+
// dispatch a "calciteInvalid" so users can set custom validation messages
264+
formComponent.dispatchEvent(new CustomEvent("calciteInvalid", { bubbles: true, composed: true }));
265+
263266
displayValidationMessage(formComponent, {
264267
message: hiddenInput?.validationMessage,
265268
icon: true,

0 commit comments

Comments
 (0)