validateSubmit
Overview
validateSubmit is a function that wraps your submission callback with validation logic. It validates the form data against the schema before executing your callback, and optionally handles validation errors.
Signature
ts
const { validateSubmit } = useVueValidateZod(schema, modelValue);
const handleSubmit = validateSubmit(
callback: (value: z.output<typeof schema>) => void,
options?: {
handleValidateError?: (
error: PartialRecord<StringPaths<z.infer<typeof schema>>, string[]>,
) => void;
},
) => () => Promise<void>Parameters
callback
- Type:
(value: OutputType) => void - Required: Yes
- Description: Function to be executed if validation succeeds. Receives the validated data.
options.handleValidateError
- Type:
(error: ErrorMap) => void - Required: No
- Description: Callback executed if validation fails. Receives an object mapping field paths to error message arrays.
Behavior
- Validates the current form data against the schema
- Sets
isSubmittedtotrue - If validation succeeds:
- Calls your
callbackwith the validated data - Resets
isSubmittedtofalse
- Calls your
- If validation fails:
- Calls
handleValidateErrorif provided - Does not call your callback
- Calls
Example
vue
<script setup lang="ts">
import { useVueValidateZod } from 'use-vue-validate-schema/zodV3';
import { ref } from 'vue';
import { z } from 'zod/v3';
const schema = z.object({
username: z.string().min(1).max(10),
email: z.string().email(),
});
const modelValue = ref<z.input<typeof schema>>({
username: '',
email: '',
});
const { validateSubmit } = useVueValidateZod(schema, modelValue);
const handleSubmit = validateSubmit(
(validValue) => {
console.log('Submission successful:', validValue);
// Send data to server
},
{
handleValidateError(errors) {
console.log('Validation failed:', errors);
// Show error message to user
},
},
);
</script>
<template>
<form @submit.prevent="handleSubmit">
<input v-model="modelValue.username" />
<input v-model="modelValue.email" />
<button type="submit">Submit</button>
</form>
</template>Notes
- The returned function is
asyncand can be awaited isSubmittedis set totrueduring validation, which affects whenErrorMessagedisplays errors- After successful submission,
isSubmittedis reset tofalse - Validation runs even if the form hasn't been modified