Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,9 @@ async function onSubmit(event: FormSubmitEvent<Schema>) {
}

async function onError(event: FormErrorEvent) {
if (event?.errors?.[0]?.id) {
const element = document.getElementById(event.errors[0].id)
element?.focus()
element?.scrollIntoView({ behavior: 'smooth', block: 'center' })
const error = event.errors[0]
if (error) {
toast.add({ title: 'Error', description: `Please check the form ${error.name}.`, color: 'error' })
}
}
</script>
Expand Down
6 changes: 5 additions & 1 deletion docs/content/docs/2.components/form.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,11 @@ You can listen to the `@error` event to handle errors. This event is triggered w
- `name` - the `name` of the `FormField`
- `message` - the error message to display.

Here's an example that focuses the first input element with an error after the form is submitted:
::tip
By default, the form automatically focuses the first field with an error when submission fails through the `focus-on-error` prop. You can disable this by passing `:focus-on-error="false"`.
::

Here's an example of using the `@error` event to add custom behavior, such as displaying a toast notification when validation fails:

::component-example
---
Expand Down
13 changes: 12 additions & 1 deletion src/runtime/components/Form.vue
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ export type FormProps<S extends FormSchema, T extends boolean = true, N extends
* @defaultValue `true`
*/
loadingAuto?: boolean
/**
* When `true`, the form automatically focuses the first field with an error on failed submission.
* @defaultValue `true`
*/
focusOnError?: boolean
Comment thread
rdjanuar marked this conversation as resolved.
class?: any
ui?: { base?: any }
onSubmit?: ((event: FormSubmitEvent<FormData<S, T>>) => void | Promise<void>) | (() => void | Promise<void>)
Expand All @@ -82,7 +87,7 @@ import { useAppConfig } from '#imports'
import { formOptionsInjectionKey, formInputsInjectionKey, formBusInjectionKey, formLoadingInjectionKey, formErrorsInjectionKey, formStateInjectionKey } from '../composables/useFormField'
import { tv } from '../utils/tv'
import { useComponentProps } from '../composables/useComponentProps'
import { validateSchema, getAtPath, setAtPath } from '../utils/form'
import { validateSchema, getAtPath, setAtPath, scrollToErrorEl } from '../utils/form'
import { FormValidationException } from '../types/form'

type I = InferInput<S>
Expand All @@ -93,6 +98,7 @@ const _props = withDefaults(defineProps<FormProps<S, T, N>>(), {
return ['input', 'blur', 'change'] as FormInputEvents[]
},
validateOnInputDelay: 300,
focusOnError: true,
transform: () => true as T,
loadingAuto: true
})
Expand Down Expand Up @@ -288,6 +294,11 @@ async function onSubmitWrapper(payload: Event) {
} finally {
loading.value = false
}

if (props.focusOnError && errors.value.length > 0) {
await nextTick()
scrollToErrorEl(errors.value)
}
}

// eslint-disable-next-line vue/no-dupe-keys
Expand Down
12 changes: 11 additions & 1 deletion src/runtime/utils/form.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { StandardSchemaV1 } from '@standard-schema/spec'
import type { Struct } from 'superstruct'
import type { FormSchema, ValidateReturnSchema } from '../types/form'
import type { FormErrorWithId, FormSchema, ValidateReturnSchema } from '../types/form'

export function isSuperStructSchema(schema: any): schema is Struct<any, any> {
return (
Expand Down Expand Up @@ -114,3 +114,13 @@ export function setAtPath<T extends object>(

return data
}

export function scrollToErrorEl(errors: FormErrorWithId[]) {
const error = errors[0]
if (error) {
const el = document.getElementById(error.id!)
if (el) {
el.focus()
}
}
}
Comment thread
rdjanuar marked this conversation as resolved.
18 changes: 18 additions & 0 deletions test/components/Form.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,24 @@ describe('Form', () => {
expect(passwordField.text()).toBe('Invalid input: expected string, received undefined')
})

it('focuses on first error element on submit error', async () => {
const emailInputMock = { focus: vi.fn() }
const passwordInputMock = { focus: vi.fn() }
const getElementByIdSpy = vi.spyOn(document, 'getElementById').mockImplementation((id) => {
if (id === 'email') return emailInputMock as any
if (id === 'password') return passwordInputMock as any
return null
})

await form.submit()
await flushPromises()

expect(emailInputMock.focus).toHaveBeenCalledTimes(1)
expect(passwordInputMock.focus).toHaveBeenCalledTimes(0)

getElementByIdSpy.mockRestore()
})

it('validate on submit works', async () => {
state.email = 'bob@dylan.com'
state.password = 'strongpassword'
Expand Down
Loading