Skip to content

Commit

Permalink
add form validation to select
Browse files Browse the repository at this point in the history
  • Loading branch information
deebloo committed Jan 2, 2025
1 parent d7e4de5 commit 2ce5cea
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
23 changes: 21 additions & 2 deletions src/lib/select/select.element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ export class USASelectElement extends HTMLElement {
@attr()
accessor name = "";

@attr()
accessor required = false;

#select = query("select");
#internals = this.attachInternals();

Expand All @@ -86,14 +89,16 @@ export class USASelectElement extends HTMLElement {
select.value = this.value;
select.name = this.name;

this.#internals.setFormValue(this.value);
this.#syncFormState();
}

@listen("change")
onSelectChange() {
const select = this.#select();

this.#internals.setFormValue(select.value);
this.value = select.value;

this.#syncFormState();
}

@listen("usa::select::option::added")
Expand All @@ -105,4 +110,18 @@ export class USASelectElement extends HTMLElement {
const select = this.#select();
select.append(target.option);
}

#syncFormState() {
this.#internals.setFormValue(this.value);

if (this.required && !this.value) {
this.#internals.setValidity(
{ valueMissing: true },
"Required",
this.#select()
);
} else {
this.#internals.setValidity({});
}
}
}
16 changes: 16 additions & 0 deletions src/lib/select/select.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,20 @@ describe("usa-select", () => {

assert.equal(value.get("example"), "third");
});

it("should not submit when not valid", async () => {
const form = await fixture<HTMLFormElement>(html`
<form>
<usa-select name="example" required>
Hello World
<usa-select-option value="first">First</usa-select-option>
<usa-select-option value="second">Second</usa-select-option>
<usa-select-option value="third">Third</usa-select-option>
</usa-select>
</form>
`);

assert.equal(form.checkValidity(), false);
});
});

0 comments on commit 2ce5cea

Please sign in to comment.