Web / TanStack Interview Questions
How do you add synchronous and asynchronous field validation in TanStack Form?
Validators run on onChange, onBlur, or onSubmit, synchronously or asynchronously. Async validators support debounce to avoid API calls on every keystroke.
<script setup lang="ts">
import { useForm } from "@tanstack/vue-form"
import { zodValidator } from "@tanstack/zod-form-adapter"
import { z } from "zod"
const form=useForm({
defaultValues: { username:"", email:"" },
validatorAdapter: zodValidator(),
onSubmit: async ({ value })=>{ await register(value) },
})
</script>
<template>
<form @submit.prevent="form.handleSubmit()">
<!-- Sync Zod validation -->
<form.Field name="username"
:validators="{
onChange: z.string().min(3,'Min 3 characters'),
onBlur: z.string().regex(/^[a-z0-9]+$/,'Lowercase/numbers only'),
}"
>
<template #default="{ field }">
<input :value="field.state.value" @blur="field.handleBlur"
@input="field.handleChange(($event.target as HTMLInputElement).value)" />
<p v-for="e in field.state.meta.errors" :key="e">{{e}}</p>
</template>
</form.Field>
<!-- Async validation with debounce -->
<form.Field name="email"
:validators="{
onChangeAsync: async ({ value })=>{
const taken=await checkEmailTaken(value)
return taken ? 'Email already registered' : undefined
},
onChangeAsyncDebounceMs: 500,
}"
>
<template #default="{ field }">
<input :value="field.state.value"
@input="field.handleChange(($event.target as HTMLInputElement).value)" />
<span v-if="field.state.meta.isValidating">Checking...</span>
<p v-for="e in field.state.meta.errors" :key="e">{{e}}</p>
</template>
</form.Field>
<button type="submit">Register</button>
</form>
</template>
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
