feat(Form): add superstruct validation (#2363)

Co-authored-by: Benjamin Canac <canacb1@gmail.com>
Co-authored-by: Romain Hamel <rom.hml@gmail.com>
This commit is contained in:
rizkyyy
2024-10-19 19:07:22 +07:00
committed by GitHub
parent 7802aacf3f
commit 5385944359
10 changed files with 166 additions and 5 deletions

View File

@@ -3,6 +3,7 @@ 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'
import type { GenericSchema as ValibotSchema, GenericSchemaAsync as ValibotSchemaAsync, SafeParser as ValibotSafeParser, SafeParserAsync as ValibotSafeParserAsync } from 'valibot'
import type { Struct } from 'superstruct'
import type { FormError } from '../types/form'
export function isYupSchema(schema: any): schema is YupObjectSchema<any> {
@@ -29,6 +30,15 @@ export async function getYupErrors(state: any, schema: YupObjectSchema<any>): Pr
}
}
export function isSuperStructSchema(schema: any): schema is Struct<any, any> {
return (
'schema' in schema
&& typeof schema.coercer === 'function'
&& typeof schema.validator === 'function'
&& typeof schema.refiner === 'function'
)
}
export function isZodSchema(schema: any): schema is ZodSchema {
return schema.parse !== undefined
}
@@ -98,3 +108,15 @@ export async function getStandardErrors(
message: issue.message
})) || []
}
export async function getSuperStructErrors(state: any, schema: Struct<any, any>): Promise<FormError[]> {
const [err] = schema.validate(state)
if (err) {
const errors = err.failures()
return errors.map(error => ({
message: error.message,
name: error.path.join('.')
}))
}
return []
}