Skip to content

Instantly share code, notes, and snippets.

@soelen
Created February 4, 2023 00:14
Show Gist options
  • Save soelen/5a34780ee9f1c260076f319e2631f9b9 to your computer and use it in GitHub Desktop.
Save soelen/5a34780ee9f1c260076f319e2631f9b9 to your computer and use it in GitHub Desktop.
Form Participation - Required
import { css, html, LitElement, TemplateResult } from 'lit';
import { customElement, property, query } from 'lit/decorators.js';
import { live } from 'lit/directives/live.js';
import { FormControlMixin, requiredValidator } from '@open-wc/form-control';
@customElement( 'an-input' )
export class AnInput extends FormControlMixin(LitElement) {
static formControlValidator = [requiredValidator];
static styles = css`
/** Custom styles here potentially for a design system */
`;
@property({ type: Boolean, reflect: true }) required = false;
@property() value = '';
@property() validationMessage = '';
@query('input') validationTarget: HTMLInputElement | null | undefined;
render(): TemplateResult {
return html`
<label for="input"><slot></slot></label>
<input
aria-describedby="helper-text"
id="input"
type="text"
.required="${live(this.required)}"
.value="${live(this.value)}"
@input="${this._onChange}"
>
<span id="helper-text">${this.validationMessage}</span>`;
}
validationMessageCallback(message: string): void {
this.validationMessage = message;
}
updated(changedProperties: Map<string, unknown>): void {
if (changedProperties.has('value')) {
this.setValue(this.value);
}
}
private _onChange(event: Event & { target: HTMLInputElement}): void {
this.value = event.target.value;
}
}
declare global {
interface HTMLElementTagNameMap {
'an-input': AnInput,
}
}
import { LitElement, css, html } from 'lit'
import { customElement, property } from 'lit/decorators.js'
import './an-input';
@customElement( 'an-setname' )
export class AnSetname extends LitElement {
render() {
return html`
<form
@submit="${ this._onSubmit }"
>
<an-input
name="xen"
required
>affi</an-input>
<button>Submit</button>
</form>
`
}
_onSubmit = ( event: SubmitEvent ) => {
event.preventDefault();
console.log('form submitted even if required field is empty');
}
}
declare global {
interface HTMLElementTagNameMap {
'an-setname': AnSetname,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment