Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Supporting async validation in createServerValidate #855

Merged
Merged
Show file tree
Hide file tree
Changes from 5 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
18 changes: 13 additions & 5 deletions packages/react-form/src/nextjs/createServerValidate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,21 @@ import type { ServerFormState } from './types'

type OnServerValidateFn<TFormData> = (props: {
value: TFormData
}) => ValidationError
}) => ValidationError | Promise<ValidationError>

type OnServerValidateOrFn<
TFormData,
TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
> =
TFormValidator extends Validator<TFormData, infer FFN>
? FFN | OnServerValidateFn<TFormData>
: OnServerValidateFn<TFormData>

interface CreateServerValidateOptions<
TFormData,
TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
> extends FormOptions<TFormData, TFormValidator> {
onServerValidate: OnServerValidateFn<TFormData>
onServerValidate: OnServerValidateOrFn<TFormData, TFormValidator>
}

export const createServerValidate =
Expand All @@ -30,17 +38,17 @@ export const createServerValidate =
async (formData: FormData, info?: Parameters<typeof decode>[1]) => {
const { validatorAdapter, onServerValidate } = defaultOpts

const runValidator = (propsValue: { value: TFormData }) => {
const runValidator = async (propsValue: { value: TFormData }) => {
if (validatorAdapter && typeof onServerValidate !== 'function') {
return validatorAdapter().validate(propsValue, onServerValidate)
return validatorAdapter().validateAsync(propsValue, onServerValidate)
}

return (onServerValidate as OnServerValidateFn<TFormData>)(propsValue)
}

const values = decode(formData, info) as never as TFormData

const onServerError = runValidator({ value: values })
const onServerError = await runValidator({ value: values })

if (!onServerError) return

Expand Down
18 changes: 13 additions & 5 deletions packages/react-form/src/start/createServerValidate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,21 @@ type Ctx = Parameters<FetchFn<FormData, unknown>>[1]

type OnServerValidateFn<TFormData> = (props: {
value: TFormData
}) => ValidationError
}) => ValidationError | Promise<ValidationError>

type OnServerValidateOrFn<
TFormData,
TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
> =
TFormValidator extends Validator<TFormData, infer FFN>
? FFN | OnServerValidateFn<TFormData>
: OnServerValidateFn<TFormData>

interface CreateServerValidateOptions<
TFormData,
TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
> extends FormOptions<TFormData, TFormValidator> {
onServerValidate: OnServerValidateFn<TFormData>
onServerValidate: OnServerValidateOrFn<TFormData, TFormValidator>
}

export const createServerValidate =
Expand All @@ -34,9 +42,9 @@ export const createServerValidate =
async (ctx: Ctx, formData: FormData, info?: Parameters<typeof decode>[1]) => {
const { validatorAdapter, onServerValidate } = defaultOpts

const runValidator = (propsValue: { value: TFormData }) => {
const runValidator = async (propsValue: { value: TFormData }) => {
if (validatorAdapter && typeof onServerValidate !== 'function') {
return validatorAdapter().validate(propsValue, onServerValidate)
return validatorAdapter().validateAsync(propsValue, onServerValidate)
}

return (onServerValidate as OnServerValidateFn<TFormData>)(propsValue)
Expand All @@ -46,7 +54,7 @@ export const createServerValidate =

const data = decode(formData, info) as never as TFormData

const onServerError = runValidator({ value: data })
const onServerError = await runValidator({ value: data })

if (!onServerError) return

Expand Down
3 changes: 2 additions & 1 deletion packages/zod-form-adapter/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@
"src"
],
"dependencies": {
"@tanstack/form-core": "workspace:*"
"@tanstack/form-core": "workspace:*",
"@tanstack/react-form": "workspace:*"
},
"devDependencies": {
"zod": "^3.23.8"
Expand Down
116 changes: 116 additions & 0 deletions packages/zod-form-adapter/tests/createServerValidate.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { describe, expect, it } from 'vitest'

import { createServerValidate } from '@tanstack/react-form/nextjs'
import { z } from 'zod'
import { zodValidator } from '../src/index'
import { sleep } from './utils'

describe('zod createServerValidate api', () => {
it('should run z.string validation', async () => {
const serverValidate = createServerValidate({
validatorAdapter: zodValidator(),
onServerValidate: z.object({
name: z.string().min(3, 'You must have a length of at least 3'),
}),
})

const formData1 = new FormData()
formData1.append('name', 'a')
expect(
await serverValidate(formData1).catch((e) => e.formState.errors),
).toEqual(['You must have a length of at least 3'])

const formData2 = new FormData()
formData2.append('name', 'asdf')
expect(await serverValidate(formData2)).toBeUndefined()
})

it('should run fn with zod validation option enabled', async () => {
const serverValidate = createServerValidate({
validatorAdapter: zodValidator(),
onServerValidate: ({ value }: { value: { name: string } }) =>
value.name === 'a' ? 'Test' : undefined,
})

const formData1 = new FormData()
formData1.append('name', 'a')
expect(
await serverValidate(formData1).catch((e) => e.formState.errors),
).toEqual(['Test'])

const formData2 = new FormData()
formData2.append('name', 'asdf')
expect(await serverValidate(formData2)).toBeUndefined()
})

it('should run z.string async validation', async () => {
const serverValidate = createServerValidate({
validatorAdapter: zodValidator(),
onServerValidate: z.object({
name: z.string().refine(
async (val) => {
await sleep(1)
return val.length > 3
},
{
message: 'Testing 123',
},
),
}),
})

const formData1 = new FormData()
formData1.append('name', 'a')
expect(
await serverValidate(formData1).catch((e) => e.formState.errors),
).toEqual(['Testing 123'])

const formData2 = new FormData()
formData2.append('name', 'asdf')
expect(await serverValidate(formData2)).toBeUndefined()
})

it('should run async fn with zod validation option enabled', async () => {
const serverValidate = createServerValidate({
validatorAdapter: zodValidator(),
onServerValidate: async ({ value }: { value: { name: string } }) => {
await sleep(1)
return value.name === 'a' ? 'Test' : undefined
},
})

const formData1 = new FormData()
formData1.append('name', 'a')
expect(
await serverValidate(formData1).catch((e) => e.formState.errors),
).toEqual(['Test'])

const formData2 = new FormData()
formData2.append('name', 'asdf')
expect(await serverValidate(formData2)).toBeUndefined()
})

it('should transform errors to display all error message', async () => {
const serverValidate = createServerValidate({
validatorAdapter: zodValidator(),
onServerValidate: z.object({
name: z
.string()
.min(3, 'You must have a length of at least 3')
.uuid('UUID'),
}),
})

const formData1 = new FormData()
formData1.append('name', 'aa')
expect(
await serverValidate(formData1).catch((e) => e.formState.errors),
).toEqual(['You must have a length of at least 3, UUID'])

const formData2 = new FormData()
formData2.append('name', 'aaa')
expect(
await serverValidate(formData2).catch((e) => e.formState.errors),
).toEqual(['UUID'])
})
})
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.