On submit focus first input having a validation error.

This commit is contained in:
baldo 2022-09-01 14:04:54 +02:00
parent 8d73e1bb80
commit 903a1bcf8a
2 changed files with 28 additions and 9 deletions

View file

@ -31,8 +31,20 @@ function onSubmit() {
const valid = validate(); const valid = validate();
if (valid) { if (valid) {
emit("submit"); emit("submit");
} else {
for (const component of validationComponents.value) {
if (
component.isMounted &&
component.exposed?.validate &&
component.exposed?.focus
) {
if (!component.exposed.validate()) {
component.exposed.focus();
return;
}
}
}
} }
// TODO: Else scroll to first error and focus input.
} }
</script> </script>

View file

@ -30,6 +30,7 @@ const displayLabel = computed(() =>
: undefined : undefined
); );
const label = ref<HTMLInputElement>();
const input = ref<HTMLInputElement>(); const input = ref<HTMLInputElement>();
const valid = ref(true); const valid = ref(true);
const validated = ref(false); const validated = ref(false);
@ -72,13 +73,6 @@ function onInput() {
}); });
} }
function reset() {
withInputElement((element) => {
element.value = "";
onInput();
});
}
function validate(): boolean { function validate(): boolean {
const element = input.value; const element = input.value;
if (!element) { if (!element) {
@ -90,7 +84,20 @@ function validate(): boolean {
return valid.value; return valid.value;
} }
function reset() {
withInputElement((element) => {
element.value = "";
onInput();
});
}
function focus() {
label.value?.scrollIntoView();
input.value?.focus();
}
defineExpose({ defineExpose({
focus,
validate, validate,
}); });
@ -101,7 +108,7 @@ onMounted(() => {
<template> <template>
<div class="validation-form-input"> <div class="validation-form-input">
<label> <label ref="label">
{{ displayLabel }} {{ displayLabel }}
<ExpandableHelpBox v-if="props.help" :text="props.help" /> <ExpandableHelpBox v-if="props.help" :text="props.help" />