UNPKG

@nuxt/ui

Version:

A UI Library for Modern Web Apps, powered by Vue & Tailwind CSS.

109 lines (108 loc) 2.82 kB
export function isYupSchema(schema) { return schema.validate && schema.__isYupSchema__; } export function isYupError(error) { return error.inner !== void 0; } export function isSuperStructSchema(schema) { return "schema" in schema && typeof schema.coercer === "function" && typeof schema.validator === "function" && typeof schema.refiner === "function"; } export function isJoiSchema(schema) { return schema.validateAsync !== void 0 && schema.id !== void 0; } export function isJoiError(error) { return error.isJoi === true; } export function isStandardSchema(schema) { return "~standard" in schema; } export async function validateStandardSchema(state, schema) { const result = await schema["~standard"].validate(state); if (result.issues) { return { errors: result.issues?.map((issue) => ({ name: issue.path?.map((item) => typeof item === "object" ? item.key : item).join(".") || "", message: issue.message })) || [], result: null }; } return { errors: null, result: result.value }; } async function validateYupSchema(state, schema) { try { const result = await schema.validate(state, { abortEarly: false }); return { errors: null, result }; } catch (error) { if (isYupError(error)) { const errors = error.inner.map((issue) => ({ name: issue.path ?? "", message: issue.message })); return { errors, result: null }; } else { throw error; } } } async function validateSuperstructSchema(state, schema) { const [err, result] = schema.validate(state); if (err) { const errors = err.failures().map((error) => ({ message: error.message, name: error.path.join(".") })); return { errors, result: null }; } return { errors: null, result }; } async function validateJoiSchema(state, schema) { try { const result = await schema.validateAsync(state, { abortEarly: false }); return { errors: null, result }; } catch (error) { if (isJoiError(error)) { const errors = error.details.map((issue) => ({ name: issue.path.join("."), message: issue.message })); return { errors, result: null }; } else { throw error; } } } export function validateSchema(state, schema) { if (isStandardSchema(schema)) { return validateStandardSchema(state, schema); } else if (isJoiSchema(schema)) { return validateJoiSchema(state, schema); } else if (isYupSchema(schema)) { return validateYupSchema(state, schema); } else if (isSuperStructSchema(schema)) { return validateSuperstructSchema(state, schema); } else { throw new Error("Form validation failed: Unsupported form schema"); } }