feat(Form): add Standard Schema support (#2303)

Co-authored-by: Benjamin Canac <canacb1@gmail.com>
This commit is contained in:
Fabian Hiller
2024-10-07 17:25:52 -04:00
committed by GitHub
parent aa8fa5be3a
commit 0955c07edd
5 changed files with 264 additions and 247 deletions

View File

@@ -1,3 +1,4 @@
import type { StandardSchema } from '@standard-schema/spec'
import type { ZodSchema } from 'zod'
import type { ValidationError as JoiError, Schema as JoiSchema } from 'joi'
import type { ObjectSchema as YupObjectSchema, ValidationError as YupError } from 'yup'
@@ -71,7 +72,7 @@ export function isValibotSchema(schema: any): schema is ValibotSchema | ValibotS
return '_run' in schema || (typeof schema === 'function' && 'schema' in schema)
}
export async function getValibotError(
export async function getValibotErrors(
state: any,
schema: ValibotSchema | ValibotSchemaAsync | ValibotSafeParser<any, any> | ValibotSafeParserAsync<any, any>
): Promise<FormError[]> {
@@ -82,3 +83,18 @@ export async function getValibotError(
message: issue.message
})) || []
}
export function isStandardSchema(schema: any): schema is StandardSchema {
return '~standard' in schema
}
export async function getStandardErrors(
state: any,
schema: StandardSchema
): Promise<FormError[]> {
const result = await schema['~validate']({ value: state })
return result.issues?.map(issue => ({
name: issue.path?.map(item => typeof item === 'object' ? item.key : item).join('.') || '',
message: issue.message
})) || []
}