npm version npm downloads Github Actions CI License
Schema validation for h3 using Valibot π€
# Using npm npm install h3-valibot # Using pnpm pnpm install h3-valibot # Using bun bun add h3-valibot
import { useValidatedBody, v, vh } from 'h3-valibot' import { createApp, createRouter, eventHandler } from 'h3'; import { email, minLength, string, objectAsync } from 'valibot'; export const app = createApp(); const LoginSchema = v.object({ email: vh.email, password: v.pipe(v.string(), v.minLength(8)), }); const router = createRouter(); app.use(router); router.post("/login", eventHandler(async (event) => { const body = await useValidatedBody(event, LoginSchema); return body; }), );
// same as above router.post("/login", eventHandler(async (event) => { const body = await useSafeValidatedBody(event, LoginSchema); if (!body.success) // do something return body.output; }), );
h3-valibot provides a series of utils and their safe variants (don't throw an h3 error):
useValidatedBodyuseValidatedInputuseValidatedParamsuseValidatedQueryuseSafeValidatedBodyuseSafeValidatedInputuseSafeValidatedParamsuseSafeValidatedQuery
Each one accepts an h3 event, a valibot schema and optionally a parser config.
It also provides a set of helpers via vh object, mainly related to string validation, particularly useful during the prototyping phase of any project. For production use we still suggest to create dedicated schemas with project-related error messages and fallbacks.
boolAsStringcheckboxAsStringdateAsStringintAsStringnumAsStringemailuuid
For more details or examples please refer to their JSdocs or source code.
h3-valibot throws an ValiError when the validation fails:
Example
{
"statusCode": 400,
"statusMessage": "Bad Request",
"stack": [],
"data": {
"issues": [
{
"validation": "email",
"origin": "value",
"message": "Invalid email",
"input": "github@conner-bachmande",
"path": [
{
"schema": "object",
"input": {
"email": "github@conner-bachmande",
"password": "12345678"
},
"key": "email",
"value": "github@conner-bachmande"
}
],
"reason": "string"
}
],
"name": "ValiError"
}
}This library supports Nuxt's auto-imports, just add it in your nuxt.config.ts:
export default defineNuxtConfig({ modules: [ // ... 'h3-valibot/nuxt', ], })
Published under MIT - Made with β€οΈ by Conner Bachmann