Skip to content

Commit

Permalink
feat: add calciteInvalid event for form validation (#9211)
Browse files Browse the repository at this point in the history
**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`.
  • Loading branch information
benelan committed Apr 30, 2024
1 parent becb2e3 commit a504508
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -167,13 +167,19 @@ export function formAssociated(

const submitButton = await page.find("#submitButton");
const spyEvent = await page.spyOnEvent(getClearValidationEventName(tag));
const spyInvalidEvent = await page.spyOnEvent("calciteInvalid");

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

await assertPreventsFormSubmission(page, component, submitButton, requiredValidationMessage);
expect(spyInvalidEvent).toHaveReceivedEventTimes(1);

await assertClearsValidationOnValueChange(page, component, options, spyEvent, tag);
expect(spyInvalidEvent).toHaveReceivedEventTimes(1);

await assertUserMessageNotOverridden(page, component, submitButton);
expect(spyInvalidEvent).toHaveReceivedEventTimes(2);
}

function ensureName(html: string, componentTag: string): string {
Expand Down
3 changes: 3 additions & 0 deletions packages/calcite-components/src/utils/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,9 @@ function invalidHandler(event: Event) {
// prevent the browser from showing the native validation popover
event?.preventDefault();

// dispatch a "calciteInvalid" so users can set custom validation messages
formComponent.dispatchEvent(new CustomEvent("calciteInvalid", { bubbles: true, composed: true }));

displayValidationMessage(formComponent, {
message: hiddenInput?.validationMessage,
icon: true,
Expand Down

0 comments on commit a504508

Please sign in to comment.