valid

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2024 License: MIT Imports: 9 Imported by: 0

README

Valid 🛡️

Go Reference Go Report Card Coverage Status License

A lightweight, fluent validation library for Go with zero dependencies. Features type-safe validators and built-in internationalization support.

Features ✨

  • 🔄 Fluent chainable API
  • 🎯 Type-specific validations
  • 🌍 Built-in i18n support (EN/ES)
  • ⚡ Zero external dependencies
  • 🔍 Comprehensive error messages
  • 💪 Strong type safety
  • 🧪 100% test coverage

Installation 📦

go get -u github.com/techforge-lat/valid

Quick Start 🚀

package main

import (
    "fmt"
    "github.com/techforge-lat/valid"
)

type User struct {
    Age       int
    Email     string
    Score     float64
    Tags      []string
}

func (u *User) Validate() error {
    // Initialize validator with language preference
    v := valid.New(valid.ES) // or valid.EN for English

    v.Int("age", u.Age).
        Required().
        Between(18, 130)

    v.String("email", u.Email).
        Required().
        Email()

    v.Float("score", u.Score).
        Required().
        Between(0, 100).
        Precision(2)

    v.Slice("tags", u.Tags).
        Required().
        MinLength(1).
        MaxLength(5)

    if v.HasErrors() {
        return v.Errors()
    }

    return nil
}

func main() {
    user := &User{
        Age:     15,
        Email:   "invalid@email",
        Score:   75.456,
        Tags:    []string{},
    }

    if err := user.Validate(); err != nil {
        fmt.Printf("Errores de validación:\n%s\n", err)
    }
}

Internationalization 🌍

The library supports English and Spanish out of the box, with flexible language configuration:

Global Default Language
// Set default language globally (e.g., in init() or main())
valid.SetDefaultLanguage(valid.ES)

// Create validator with default language
v := valid.New()

// Check current default language
lang := valid.GetDefaultLanguage()
Instance-specific Language
// Override default language for specific validator
v1 := valid.New(valid.WithLanguage(valid.EN))
v2 := valid.New(valid.WithLanguage(valid.ES))
vDefault := valid.New() // Uses global default language
Custom Translations
// Add custom translations
valid.AddTranslation("custom_rule", valid.EN, "validation failed: %s")
valid.AddTranslation("custom_rule", valid.ES, "validación fallida: %s")

// Add multiple translations
valid.AddTranslations(map[string]map[valid.Language]string{
    "custom_rule": {
        valid.EN: "validation failed: %s",
        valid.ES: "validación fallida: %s",
    },
})

Available Validators 📝

String Validation
v.String("field", value).
    Required().
    MinLength(5).
    MaxLength(100).
    Email().
    URL().
    Pattern(regexp).
    Password()
Integer Validation
v.Int("field", value).
    Required().
    Min(0).
    Max(100).
    Between(18, 65).
    Positive().
    MultipleOf(5)
Float Validation
v.Float("field", value).
    Required().
    Positive().
    Between(0, 100).
    Precision(2)
Slice Validation
v.Slice("field", value).
    Required().
    MinLength(1).
    MaxLength(10).
    Each(func(v *valid.Validator, i int, item T) {
        // Validate each item
    })

Error Handling 🚨

Errors are returned in the selected language:

// English
type ValidationErrors []ValidationError
err.Error() // Returns: "age: must be between 18 and 130; email: invalid email format"

// Spanish
err.Error() // Returns: "age: debe estar entre 18 y 130; email: formato de email inválido"

Best Practices 💡

  1. Create a validator instance with your preferred language:
v := valid.New(valid.ES) // or valid.EN
  1. Chain validations fluently:
v.String("password", password).
    Required().
    MinLength(8).
    Password()
  1. Add custom translations if needed:
valid.AddTranslation("my_rule", valid.EN, "custom validation message: %s")
valid.AddTranslation("my_rule", valid.ES, "mensaje de validación personalizado: %s")

Contributing 🤝

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License 📄

This project is licensed under the MIT License - see the LICENSE file for details.

Support 💬

  • Create an issue for bug reports
  • Start a discussion for feature requests
  • Check out the documentation

Acknowledgments 🙏

Special thanks to all contributors and users who have helped shape this library.

Made with ❤️ by [Your Name]

Documentation

Overview

valid/slice.go

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddTranslation

func AddTranslation(key string, lang Language, message string)

AddTranslation permite agregar o modificar traducciones en runtime

func AddTranslations

func AddTranslations(messages map[string]map[Language]string)

AddTranslations permite agregar múltiples traducciones a la vez

func SetDefaultLanguage added in v0.2.0

func SetDefaultLanguage(lang Language)

SetDefaultLanguage establece el idioma por defecto a nivel global

Types

type FloatValidator

type FloatValidator struct {
	// contains filtered or unexported fields
}

func (*FloatValidator) Between

func (fv *FloatValidator) Between(min, max float64) *FloatValidator

func (*FloatValidator) Max

func (fv *FloatValidator) Max(max float64) *FloatValidator

func (*FloatValidator) Min

func (fv *FloatValidator) Min(min float64) *FloatValidator

func (*FloatValidator) Negative

func (fv *FloatValidator) Negative() *FloatValidator

func (*FloatValidator) Positive

func (fv *FloatValidator) Positive() *FloatValidator

func (*FloatValidator) Precision

func (fv *FloatValidator) Precision(decimals int) *FloatValidator

func (*FloatValidator) Required

func (fv *FloatValidator) Required() *FloatValidator

type IntValidator

type IntValidator struct {
	// contains filtered or unexported fields
}

func (*IntValidator) Between

func (iv *IntValidator) Between(min, max int64) *IntValidator

func (*IntValidator) Max

func (iv *IntValidator) Max(max int64) *IntValidator

func (*IntValidator) Min

func (iv *IntValidator) Min(min int64) *IntValidator

func (*IntValidator) MultipleOf

func (iv *IntValidator) MultipleOf(base int64) *IntValidator

func (*IntValidator) Negative

func (iv *IntValidator) Negative() *IntValidator

func (*IntValidator) Positive

func (iv *IntValidator) Positive() *IntValidator

func (*IntValidator) Required

func (iv *IntValidator) Required() *IntValidator

type Language

type Language string
const (
	EN Language = "en"
	ES Language = "es"
)

func GetDefaultLanguage added in v0.2.0

func GetDefaultLanguage() Language

GetDefaultLanguage obtiene el idioma por defecto actual

type Option added in v0.2.0

type Option func(*Validator)

Option es un tipo función para configurar el Validator

func WithLanguage added in v0.2.0

func WithLanguage(lang Language) Option

WithLanguage es una opción para establecer el idioma específico para una instancia

type SliceValidator

type SliceValidator[T any] struct {
	// contains filtered or unexported fields
}

SliceValidator con un solo tipo genérico

func (*SliceValidator[T]) MaxLength

func (sv *SliceValidator[T]) MaxLength(max int) *SliceValidator[T]

MaxLength valida la longitud máxima del slice

func (*SliceValidator[T]) MinLength

func (sv *SliceValidator[T]) MinLength(min int) *SliceValidator[T]

MinLength valida la longitud mínima del slice

func (*SliceValidator[T]) Required

func (sv *SliceValidator[T]) Required() *SliceValidator[T]

Required valida que el slice no esté vacío

type StringValidator

type StringValidator struct {
	// contains filtered or unexported fields
}

func (*StringValidator) Email

func (sv *StringValidator) Email() *StringValidator

func (*StringValidator) Length

func (sv *StringValidator) Length(length int) *StringValidator

func (*StringValidator) Matches

func (sv *StringValidator) Matches(pattern string) *StringValidator

func (*StringValidator) MaxLength

func (sv *StringValidator) MaxLength(max int) *StringValidator

func (*StringValidator) MinLength

func (sv *StringValidator) MinLength(min int) *StringValidator

func (*StringValidator) Password

func (sv *StringValidator) Password() *StringValidator

func (*StringValidator) Required

func (sv *StringValidator) Required() *StringValidator

func (*StringValidator) URL

func (sv *StringValidator) URL() *StringValidator

type UintValidator

type UintValidator struct {
	// contains filtered or unexported fields
}

func (*UintValidator) Between

func (uv *UintValidator) Between(min, max uint64) *UintValidator

func (*UintValidator) Max

func (uv *UintValidator) Max(max uint64) *UintValidator

func (*UintValidator) MaxBits

func (uv *UintValidator) MaxBits(maxBits uint) *UintValidator

func (*UintValidator) Min

func (uv *UintValidator) Min(min uint64) *UintValidator

func (*UintValidator) Port

func (uv *UintValidator) Port() *UintValidator

func (*UintValidator) PowerOfTwo

func (uv *UintValidator) PowerOfTwo() *UintValidator

func (*UintValidator) Required

func (uv *UintValidator) Required() *UintValidator

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents a single validation error

func (ValidationError) Error

func (e ValidationError) Error() string

type ValidationErrors

type ValidationErrors []ValidationError

ValidationErrors is a collection of validation errors

func (ValidationErrors) Error

func (e ValidationErrors) Error() string

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

func New

func New(opts ...Option) *Validator

Actualizamos el constructor del Validator

func (*Validator) AddError

func (v *Validator) AddError(field string, key string, args ...interface{})

func (*Validator) Errors

func (v *Validator) Errors() ValidationErrors

Errors returns all validation errors

func (*Validator) Float

func (v *Validator) Float(field string, value float64) *FloatValidator

func (*Validator) Float64Slice

func (v *Validator) Float64Slice(field string, value []float64) *SliceValidator[float64]

func (*Validator) HasErrors

func (v *Validator) HasErrors() bool

HasErrors checks if there are any validation errors

func (*Validator) Int

func (v *Validator) Int(field string, value int64) *IntValidator

func (*Validator) IntSlice

func (v *Validator) IntSlice(field string, value []int) *SliceValidator[int]

func (*Validator) Slice

func (v *Validator) Slice(field string, value []string) *SliceValidator[string]

Helper functions para crear validadores

func (*Validator) String

func (v *Validator) String(field, value string) *StringValidator

func (*Validator) Uint

func (v *Validator) Uint(field string, value uint64) *UintValidator

Jump to

Keyboard shortcuts

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