npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@heitorffonseca/laravel-zod-validator

v1.0.1

Published

Laravel-style validation package using Zod

Downloads

167

Readme

Laravel Zod Validator (Zod powered)

Um validator em TypeScript inspirado no Laravel, usando Zod por baixo, com suporte a:

  • Sintaxe de rules estilo Laravel (required|min:3|max:10)
  • Rules customizadas
  • Plugins (validator.use)
  • nullable, sometimes, required_if
  • Arrays com wildcard (items.*.field)
  • Mensagens customizadas
  • Tipagem forte
  • Integração perfeita com React / Node

✨ Motivação

Validadores existentes geralmente caem em dois extremos:

  • Muito simples (difícil de escalar)
  • Muito acoplados ao framework

Este projeto busca o meio-termo:

A ergonomia do Laravel + a segurança do Zod + a flexibilidade do TypeScript


📦 Instalação

Instale my-project com npm

  npm install @heitorffonseca/laravel-zod-validator

🚀 Uso básico

import { validate } from '@heitorffonseca/laravel-zod-validator'

validate(
  { email: '' },
  { email: 'required|email' },
  { 'email.required': 'Email obrigatório' }
)

Se falhar, uma exceção é lançada com os erros formatados.


🧩 Usando createValidator

Para controle completo do fluxo:

import { createValidator } from '@heitorffonseca/laravel-zod-validator'

const validator = createValidator(
  { email: '' },
  { email: 'required|email' },
  { 'email.email': 'Email inválido' }
)

if (!validator.validate()) {
  console.log(validator.errors())
}

Métodos disponíveis

| Método | Descrição | |--------------|--------------------------| | validate() | Executa validação | | fails() | Retorna true se falhou | | errors() | Retorna erros formatados |


📜 Sintaxe de Rules

As rules são declaradas como string, separadas por |.

{
  name: 'required|min:3|max:50',
  email: 'required|email',
  age: 'sometimes|min:18'
}

Rules disponíveis

| Rule | Descrição | |---------------------------|-------------------------| | required | Campo obrigatório | | email | Email válido | | min:n | Mínimo de caracteres | | max:n | Máximo de caracteres | | nullable | Aceita null | | sometimes | Só valida se existir | | required_if:field,value | Obrigatório condicional |


🧠 Comportamento

  • Rules são ignoradas se o valor estiver vazio ('', null, []), exceto required
  • nullable impede erros com null
  • sometimes ignora completamente o campo se não existir
  • bail (quando implementado) interrompe o pipeline

📚 Mensagens customizadas

{
  'email.required': 'Campo obrigatório',
  'email.email': 'Formato inválido'
}

Formato:

campo.rule

🔌 Rules customizadas

Você pode registrar rules customizadas globalmente.

import { use } from '@heitorffonseca/laravel-zod-validator'

use({
  rules: {
    upper: ({ schema }) =>
      schema.refine(
        v => typeof v === 'string' && v === v.toUpperCase(),
        { message: 'Deve estar em maiúsculo' }
      ),
  },
})

Uso:

createValidator(
  { name: 'abc' },
  { name: 'upper' }
)

🧩 Sistema de Plugins (use)

O sistema de plugins permite:

  • Registrar rules
  • Compartilhar extensões
  • Criar presets reutilizáveis
use({
  rules: {
    cpf: ({ schema }) =>
      schema.refine(isValidCPF, { message: 'CPF inválido' })
  }
})

📦 Validação de Arrays com Wildcard

Suporte completo a *:

createValidator(
  {
    items: [
      { name: '' },
      { name: 'Produto' }
    ]
  },
  {
    'items.*.name': 'required|min:3'
  }
)

Erros retornados

{
  'items.0.name': ['Campo obrigatório']
}

🧪 Testes

O projeto utiliza Vitest.

npm run test

Cobertura inclui:

  • Rules individuais
  • Integração completa
  • Plugins (use)
  • Wildcards
  • required_if

🏗️ Arquitetura (visão geral)

src/
├─ index.ts              # API pública
├─ error/
│  ├─ formatErrors.ts
│  └─ ValidationException.ts
├─ rule/
│  ├─ rules/
│  │  ├─ required.ts
│  │  ├─ max.ts 
│  │  ├─ requiredIf.ts
│  │  └─ ...
│  ├─ index.ts
│  ├─ register.ts
│  └─ types.d.ts
├─ schema/
│  ├─ applyRules.ts
│  ├─ buildField.ts
│  ├─ buildSchema.ts
│  └─ getMessage.ts
├─ utils/
│  ├─ expandWildcardRules.ts
│  ├─ isEmpty.ts
│  ├─ parseRule.ts
│  └─ parseRules.ts
└─ validator/
   ├─ createValidator.ts
   ├─ validate.ts
   └─ types.ts

Princípios

  • Rules não conhecem arrays
  • Wildcards são resolvidos no schema
  • Pipeline é extensível
  • API pública é estável

🤝 Contribuindo

Contribuições são bem-vindas!

  1. Fork
  2. Crie sua branch
  3. Adicione testes
  4. PR 🎉

📄 Licença

MIT