validator_fiber

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 17, 2026 License: MIT Imports: 11 Imported by: 0

README

validator_fiber

Descrição

Este projeto é um validador para o framework web Fiber. Ele fornece uma maneira simples e eficiente de validar requisições HTTP, como dados de formulários ou JSON, antes de serem processados pela sua aplicação Fiber.

Funcionalidades

Este validador encapsula a popular biblioteca github.com/go-playground/validator/v10 para oferecer validação de structs. As principais funcionalidades incluem:

  • Validação de Structs: Valida qualquer struct Go usando tags de validação (validate:"required,email", validate:"min=3", etc.).
  • Retorno de Erros Formatados: Os erros de validação são retornados em uma slice de ErrorsHandle, que contém informações como FailedField (o campo que falhou a validação), Tag (a tag de validação que causou o erro), Message (uma mensagem traduzida e legível) e Error (um booleano indicando erro).
  • Nome de campo baseado no JSON: FailedField usa a tag json da struct (não o nome do campo Go), incluindo o caminho completo em campos de structs aninhadas (ex: address.city).
  • Mensagens traduzidas: Message traz o erro pronto para exibir, em pt_BR por padrão. O idioma pode ser trocado com SetLocale (locales suportados: pt_BR e en).

Instalação

Para usar este validador em seu projeto Fiber, você pode instalá-lo usando go get:

go get github.com/stolato/validator_fiber

Uso

Para integrar o validador com sua aplicação Fiber, você pode importar o pacote e usar a função Validator em seus handlers.

Estrutura de Erros

O validador retorna uma slice de ErrorsHandle em caso de falha na validação, com a seguinte estrutura:

type ErrorsHandle struct {
	FailedField string // Nome do campo (tag json) que falhou a validação; para campos
	                   // de structs aninhadas, traz o caminho completo (ex: "address.city")
	Tag         string // A tag de validação (ex: "required", "min")
	Value       any    // O valor do campo (útil para debug)
	Message     string // Mensagem de erro traduzida, pronta para exibir (ex: "name é um campo obrigatório")
	Error       bool   // Sempre true para indicar um erro
}
Idioma das mensagens

Por padrão, Message é retornada em pt_BR. Para trocar o idioma (afeta todas as chamadas de Validator no processo), use SetLocale:

if err := validator_fiber.SetLocale("en"); err != nil {
	log.Fatal(err)
}

Locales suportados atualmente: pt_BR e en.

Exemplo Básico
// Exemplo de uso
package main

import (
	"log"

	"github.com/gofiber/fiber/v2"
	validator_fiber "github.com/stolato/validator_fiber"
)

type User struct {
	Name  string `json:"name" validate:"required,min=3,max=32"`
	Email string `json:"email" validate:"required,email"`
	Age   uint   `json:"age" validate:"required,gte=18"`
}

func main() {
	app := fiber.New()

	app.Post("/users", func(c *fiber.Ctx) error {
		user := new(User)

		if err := c.BodyParser(user); err != nil {
			return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
				"error": "Cannot parse JSON",
			})
		}

		// Validar o struct User
		if errs := validator_fiber.Validator(user); errs != nil {
			return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
				"errors": errs,
			})
		}

		// Se a validação passar, você pode prosseguir com a lógica de negócio
		return c.Status(fiber.StatusCreated).JSON(fiber.Map{
			"message": "User created successfully",
			"user":    user,
		})
	})

	log.Fatal(app.Listen(":3000"))
}

Contribuição

Contribuições são bem-vindas! Se você quiser melhorar este projeto, por favor, sinta-se à vontade para abrir uma issue ou enviar um pull request.

Licença

Este projeto é licenciado sob a licença MIT. Veja o arquivo LICENSE para mais detalhes.

Documentation

Index

Constants

View Source
const DefaultLocale = "pt_BR"

DefaultLocale is used to translate validation error messages when SetLocale is never called.

Variables

This section is empty.

Functions

func SetLocale

func SetLocale(locale string) error

SetLocale changes the language used to translate validation error messages returned in ErrorsHandle.Message. Supported locales: "pt_BR" (default) and "en". It affects every subsequent call to Validator across the whole process.

Types

type ErrorsHandle

type ErrorsHandle struct {
	// FailedField is the field's name, using its `json` tag when present.
	// For fields inside nested structs it carries the full path, dot
	// separated (eg. "address.city").
	FailedField string
	// Tag is the validation tag that failed (eg. "required", "min").
	Tag string
	// Value is the field's actual value, useful for debugging.
	Value any
	// Message is the human-readable, translated error message. The
	// language is "pt_BR" by default; see SetLocale to change it.
	Message string
	// Error is always true; it signals that this entry represents a
	// validation failure.
	Error bool
}

ErrorsHandle describes a single validation failure for one struct field.

func Validator

func Validator(item any) []ErrorsHandle

Validator validates item's exported fields against their `validate` struct tags and returns one ErrorsHandle per failed field. It returns nil when item passes validation, and an empty slice when item cannot be validated at all (eg. item is not a struct or a pointer to one).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL