Skip to content

Commit

Permalink
feat(input): expose checkValidity method (#270)
Browse files Browse the repository at this point in the history
Co-authored-by: Michel Binder <[email protected]>
  • Loading branch information
cubmic and Michel Binder authored Feb 26, 2025
1 parent b23568f commit 3786a59
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 12 deletions.
28 changes: 18 additions & 10 deletions src/components/input/Input.js
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,24 @@ export class LeuInput extends LeuElement {
return validationMessages
}

isInvalid() {
if (this.error) {
return true
}

return this._validity === null || this.novalidate
? false
: !this._validity.valid
}

/**
* Check input validation
* @returns {boolean} if valid or not
*/
checkValidity() {
return this._inputRef.value?.checkValidity() ?? false
}

/**
* Creates an error list with an item for the given validity state.
* @returns {import("lit").TemplateResult | nothing}
Expand Down Expand Up @@ -377,16 +395,6 @@ export class LeuInput extends LeuElement {
return nothing
}

isInvalid() {
if (this.error) {
return true
}

return this._validity === null || this.novalidate
? false
: !this._validity.valid
}

render() {
const isInvalid = this.isInvalid()

Expand Down
2 changes: 0 additions & 2 deletions src/components/input/stories/input.stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,6 @@ function Template(args) {
novalidate = false,
} = args

console.log(min, max)

return html`
<leu-input
value=${ifDefined(value)}
Expand Down
26 changes: 26 additions & 0 deletions src/components/input/test/input.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -469,4 +469,30 @@ describe("LeuInput", () => {

expect(el.valueAsNumber).to.be.NaN
})

it("check input is valid", async () => {
{
const el = await defaultFixture({ label: "Länge", type: "number" })
el.focus()

await sendKeys({ type: "text" })
expect(el.checkValidity()).to.be.false

await elementUpdated(el)
const error = el.shadowRoot.querySelector(".error")
expect(error).not.to.be.null
}

{
const el = await defaultFixture({ label: "Länge", type: "number" })
el.focus()

await sendKeys({ type: "123" })
expect(el.checkValidity()).to.be.true

await elementUpdated(el)
const error = el.shadowRoot.querySelector(".error")
expect(error).to.be.null
}
})
})

0 comments on commit 3786a59

Please sign in to comment.