TypeScript-first schema validation for h3 and Nuxt applications

Overview

h3-zod

npm (tag) npm bundle size NPM

Validate h3 and Nuxt 3 requests using zod schema's.

Install

npm install h3-zod

Usage

import { createServer } from 'http'
import { createApp } from 'h3'
import { useValidatedBody, useValidatedQuery, z } from 'h3-zod'

const app = createApp()

app.use('/', async (req) => {
  // Validate body
  const body = await useValidatedBody(req, z.object({
    optional: z.string().optional(),
    required: z.boolean()
  }))

  // Validate query
  const query = useValidatedQuery(req, z.object({
    required: z.string()
  }))
})

with Nuxt

// ~/server/api/todo.post.ts
import { useValidatedBody, z } from 'h3-zod'

export default defineEventHandler(async (event) => {
  const body = await useValidatedBody(event, z.object({
    optional: z.string().optional(),
    required: z.boolean()
  }))
})

Related

License

MIT

You might also like...

Lightweight and powerfull library for declarative form validation

Formurai is a lightweight and powerfull library for declarative form validation Features Setup Usage Options Methods Rules Examples Roadmap Features ?

May 13, 2022

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Dec 26, 2022

Simple, smart and pleasant validation solution.

nice-validator Simple, smart and pleasant validation solution. Download the latest release or install package via npm or bower $ npm install nice-vali

Nov 18, 2022

Themis is a validation and processing library that helps you always make sure your data is correct.

Dataffy Themis - The advanced validation library Themis is a validation and processing library that helps you always make sure your data is correct. ·

Oct 27, 2022

jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

Jan 3, 2023

String validation

validator.js A library of string validators and sanitizers. Strings only This library validates and sanitizes strings only. If you're not sure if your

Jan 5, 2023

Lightweight JavaScript form validation library inspired by CodeIgniter.

validate.js validate.js is a lightweight JavaScript form validation library inspired by CodeIgniter. Features Validate form fields from over a dozen r

Dec 15, 2022

Cross Browser HTML5 Form Validation.

Validatr Cross Browser HTML5 Form Validation. Getting Started View the documentation to learn how to use Validatr. Changelog Version 0.5.1 - 2013-03-1

Nov 1, 2022

jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

Jan 3, 2023
Comments
  • the validate body don't throw a 400

    the validate body don't throw a 400

    I am using what you are saying in your doc. The one says should send a 400 status code.

    But nothing happened when using it. Is the doc missing something ?

    opened by paper-florent 2
  • Validate ZodEffects schema

    Validate ZodEffects schema

    First of all thanks for this very useful library.

    The issue I'd like to report deals with using schema with type ZodEffects. Such schema can be produced by using z.refine on z.object as shown in example below. This produces a TS error. See https://codesandbox.io/s/morning-bash-oi6h35?file=/server/api/submit.post.ts

    import { useValidatedBody, z } from "h3-zod";
    import { defineEventHandler } from "h3";
    import dayjs from "dayjs";
    
    const bodySchema = z
      .object({
        fromDate: z.string().optional(),
        toDate: z.string().optional()
      })
      .refine(
        (schema) =>
          !!schema.fromDate && !!schema.toDate
            ? dayjs(schema.fromDate).isBefore(schema.toDate)
            : true,
        "'fromDate' has to be before 'toDate'"
      );
    
    export default defineEventHandler(async (event) => {
      const body = await useValidatedBody(event, bodySchema);
      return;
    });
    

    The solution would be to extend TQuery type like so:

    type TQuery<U extends UnknownKeysParam = any> =
      | z.ZodObject<any, U>
      | z.ZodUnion<[TQuery<U>, ...TQuery<U>[]]>
      | z.ZodIntersection<TQuery<U>, TQuery<U>>
      | z.ZodDiscriminatedUnion<string, z.Primitive, z.ZodObject<any, U>>
      | z.ZodEffects<z.ZodTypeAny>; // <-- add this line
    

    Would you like me to open a PR?

    opened by littlejon85 2
  • Validating nested ZodEffects throws TS error

    Validating nested ZodEffects throws TS error

    First of all big thanks for actively maintaining this package.

    Zod schema can use multiple refine validations, which produces type with nested ZodEffects.

    Passing this schema to h3-zod gives TS error.

    Reproduction:
    https://codesandbox.io/s/ecstatic-surf-0u8wo2?file=/server/api/submit.post.ts

    Tried this with [email protected], which handled this case OK, but further improvements were made down the line, changing the behaviour.

    EDIT: Also the resulting body type is unknown,

    opened by littlejon85 0
Releases(v0.3.10)
Owner
Robert Soriano
[object Object]
Robert Soriano
Schema-Inspector is an JSON API sanitisation and validation module.

Schema-Inspector is a powerful tool to sanitize and validate JS objects. It's designed to work both client-side and server-side and to be scalable wit

null 494 Oct 3, 2022
Dead simple Object schema validation

Yup Yup is a JavaScript schema builder for value parsing and validation. Define a schema, transform a value to match, validate the shape of an existin

Jason Quense 19.2k Jan 2, 2023
Schema validation utilities for h3, using typebox & ajv

h3-typebox JSON schema validation for h3, using typebox & ajv. Install # Using npm npm install h3-typebox # Using yarn yarn install h3-typebox # Usi

Kevin Marrec 43 Dec 10, 2022
FieldVal - multipurpose validation library. Supports both sync and async validation.

FieldVal-JS The FieldVal-JS library allows you to easily validate data and provide readable and structured error reports. Documentation and Examples D

null 137 Sep 24, 2022
Validate for XML schema and returns all the possible failures

detailed-xml-validator Validate for XML schema and returns all the possible failures Sample Rules file <?xml version = "1.0"?> <students nillable="fa

Natural Intelligence 11 Dec 20, 2022
Convert JSON examples into JSON schema (supports Swagger 2, OpenAPI 3 and 3.1)

json-to-json-schema Convert JSON examples into JSON schema. Supports JSON Schema draft-05 used in Swagger 2.0 and OpenAPI 3.0 and new draft draft-2020

Redocly 9 Sep 15, 2022
Tiny Validator for JSON Schema v4

Tiny Validator (for v4 JSON Schema) Use json-schema draft v4 to validate simple values and complex objects using a rich validation vocabulary (example

Geraint 1.2k Dec 21, 2022
Validate graphql operations against a schema

@graphql-validate With the power of GraphQL-Tools and GraphQL-JS, we are able to provide a smooth experience for validation your GraphQL operations du

Saihajpreet Singh 13 Dec 23, 2022
:white_check_mark: Easy property validation for JavaScript, Node and Express.

property-validator ✅ Easy property validation for JavaScript, Node and Express Built on top of validator.js, property-validator makes validating reque

Netto Farah 160 Dec 14, 2022