Skip to content

Commit

Permalink
validate on input with debounce
Browse files Browse the repository at this point in the history
  • Loading branch information
luca-peruzzo committed Oct 21, 2024
1 parent b578176 commit 98e236e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/login/components/input-tag/input-tag.component.html
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
@let attr = attribute();
@let index = fieldIndex();
@if (attr) {
@let type = attr.annotations.inputType | inputType;
<input
[type]="attr.annotations.inputType | inputType"
[type]="type"
[id]="attr.name"
[name]="attr.name"
[value]="value()"
Expand All @@ -26,6 +27,7 @@
[attr.step]="attr.annotations.inputTypeStep"
[kcAttributes]="attr.html5DataAnnotations"
(change)="onChange($event)"
(input)="inputListenerTypes.includes(type) && onInput($event)"
(blur)="onBlur()"
/>
@if (index !== undefined) {
Expand Down
31 changes: 31 additions & 0 deletions src/login/components/input-tag/input-tag.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ export class InputTagComponent extends ComponentReference {
override doUseDefaultCss = inject<boolean>(USE_DEFAULT_CSS);
override classes = inject<Partial<Record<ClassKey, string>>>(LOGIN_CLASSES);

inputListenerTypes = ['text', 'search', 'url', 'tel', 'email', 'password'];
#inputTimeout: any | undefined;

value = computed(() => {
const valueOrValues = this.valueOrValues();
const index = this.fieldIndex();
Expand All @@ -66,6 +69,34 @@ export class InputTagComponent extends ComponentReference {
return valueOrValues ?? null;
});

onInput(event: Event) {
if (this.#inputTimeout) {
clearTimeout(this.#inputTimeout);
}
this.#inputTimeout = setTimeout(() => {
const valueOrValues = this.valueOrValues();
this.dispatchFormAction.emit({
action: 'update',
name: this.attribute()?.name ?? '',
valueOrValues: (() => {
if (this.fieldIndex !== undefined) {
if (valueOrValues instanceof Array) {
return valueOrValues.map((value, i) => {
if (i === this.fieldIndex()) {
return (event.target as HTMLInputElement)?.value;
}

return value;
});
}
}

return (event.target as HTMLInputElement)?.value;
})()
});
}, 300);
}

onChange(event: Event) {
const valueOrValues = this.valueOrValues();
this.dispatchFormAction.emit({
Expand Down

0 comments on commit 98e236e

Please sign in to comment.