vael-ui v0.5.7

Forms guide · 3 of 8

Submitting

handleSubmit prevents the page reload, validates, and then calls onSubmit with valid values. A second submit while one runs is ignored.

onSubmit onSubmitsubmitting

onSubmit gets the schema’s output, so a z.coerce.number() arrives as a number, and a context with the form, the event, the element and the submitter. submitting is true until its promise settles. If it throws, handleSubmit rejects and submitting goes back to false.

Errors from your server setErrors

Put what your server rejects on the field with setErrors. The error shows at once and clears when that field changes. Try [email protected].

Two buttons, one form

The button that submitted is submitter, as in HTML. Give each button a name and a value, and read it in onSubmit.

<button name="action" value="draft">Save draft</button>
<button name="action" value="publish">Publish</button>

<script setup lang="ts">
const form = useForm({
  schema,
  onSubmit: (values, { submitter }) => api.save(values, submitter?.value),
})
</script>

A handler of your own handleSubmit

handleSubmit(fn) returns a submit handler that calls fn instead of onSubmit, with the same values and context. Create it in the script: an inline @submit="handleSubmit(fn)" would only create the handler, not run it.

const onSubmit = handleSubmit(async (values, { formData }) => {
  await api.save(values)
})

// <form novalidate @submit="onSubmit">

FormData onSubmit

formData in the context is the values as multipart, built when you read it. It comes from the values, so steps that aren’t on screen are in it. Nested values use the inputs’ names (address.street, members.0.name), files stay files, dates become ISO strings, and the pressed button’s name and value are added.

useForm({
  schema,
  onSubmit: (values, { formData }) =>
    fetch('/api/signup', { method: 'POST', body: formData }),
})

With TanStack Query

The form checks the values and a mutation sends them. Call the mutation from onSubmit, and put a server’s field errors back with setErrors in the mutation’s onError. handleSubmit() called from code shows every error and focuses the first invalid field, as a submit does.

const mutation = useMutation({ mutationFn: (values: Values) => api.save(values) })

const { handleSubmit } = useForm({
  schema,
  onSubmit: (values) => mutation.mutateAsync(values),
})
// <Button type="submit" :loading="mutation.isPending.value">Save</Button>