rapidval

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2025 License: MIT Imports: 4 Imported by: 0

README

RapidVal

Go Reference Go Report Card Coverage Status License

RapidVal is a high-performance, zero-dependency validation library for Go. It focuses on simplicity, extensibility, and performance while providing a clean and intuitive API.

Philosophy

  • No Reflection: Uses compile-time type safety instead of runtime reflection
  • No Dependencies: Zero external dependencies for core functionality
  • Performance First: Designed with performance in mind
  • Developer Friendly: Clean API with excellent IDE support
  • Extensible: Easy to add custom validation rules
  • i18n Ready: Built-in translation support with customizable messages

Features

  • Type-safe validation rules
  • Composable validation chains
  • Custom validation rules support
  • Built-in translation system
  • Template-friendly error messages
  • Comprehensive test coverage
  • Detailed error reporting

Installation

go get github.com/9ssi7/rapidval

Quick Start

package main

import (
	"time"

	"github.com/9ssi7/rapidval"
)

type Business struct {
	Title       string
	Description string
	FoundAt     time.Time
}

func (b *Business) Validations() rapidval.P {
	now := time.Now()
	return rapidval.P{
		rapidval.Required("Title", b.Title),
		rapidval.Required("Description", b.Description),
		rapidval.Required("FoundAt", b.FoundAt),
		rapidval.MinLength("Title", b.Title, 3),
		rapidval.MaxLength("Title", b.Title, 100),
		rapidval.MinLength("Description", b.Description, 10),
		rapidval.MaxLength("Description", b.Description, 1000),
		rapidval.DateGreaterThan("FoundAt", b.FoundAt, now),
		rapidval.DateLessThan("FoundAt", b.FoundAt, now.Add(24*time.Hour)),
	}
}

func main() {
	business := &Business{
		Title:       "RapidVal",
		Description: "RapidVal is a high-performance, zero-dependency validation library for Go.",
		FoundAt:     time.Now(),
	}
	v := rapidval.New()
	if err := v.Validate(business); err != nil {
		fmt.Println(err)
	}
}

Translation Support

RapidVal comes with a built-in translation system that allows you to customize error messages. You can use the NewTranslator function to create a new translator with your own messages or use the NewTranslatorWithMessages function to create a new translator with predefined messages.

tr := rapidval.NewTranslator()

You can also use the Translate method to translate an error message.

err := &rapidval.ValidationError{
	Field:      "Title",
	MessageKey: rapidval.MsgRequired,
}
translated := tr.Translate(err)
fmt.Println(translated)

Examples

You can find more examples in the examples directory.

Benchmarks

RapidVal is designed to be extremely fast and memory-efficient. Here are some benchmark results showing the performance of different operations:

goos: darwin
goarch: arm64
pkg: github.com/9ssi7/rapidval
cpu: Apple M3 Pro

# Single Validation Rules
BenchmarkValidations/Required-12                    10880550     129.0 ns/op    416 B/op    4 allocs/op
BenchmarkValidations/Email-12                      177856407       6.877 ns/op     0 B/op    0 allocs/op
BenchmarkValidations/MinLength-12                 1000000000       0.2787 ns/op    0 B/op    0 allocs/op
BenchmarkValidations/MaxLength-12                 1000000000       0.2796 ns/op    0 B/op    0 allocs/op
BenchmarkValidations/Between-12                   1000000000       0.2796 ns/op    0 B/op    0 allocs/op
BenchmarkValidations/DateGreaterThan-12            421514941       2.965 ns/op     0 B/op    0 allocs/op
BenchmarkValidations/DateLessThan-12               421147266       2.836 ns/op     0 B/op    0 allocs/op

# Multiple Validations
BenchmarkValidator/Multiple_Validations-12           2097082     590.5 ns/op   1447 B/op   16 allocs/op

# Translation Performance
BenchmarkTranslator/Translate-12                     3366672     356.2 ns/op    272 B/op    8 allocs/op

# Zero Value Checks
BenchmarkIsZero/string-12                         1000000000       0.7256 ns/op    0 B/op    0 allocs/op
BenchmarkIsZero/empty_string-12                   1000000000       0.7075 ns/op    0 B/op    0 allocs/op
BenchmarkIsZero/int-12                            1000000000       0.9177 ns/op    0 B/op    0 allocs/op
BenchmarkIsZero/zero_int-12                       1000000000       0.8901 ns/op    0 B/op    0 allocs/op
BenchmarkIsZero/bool-12                           1000000000       0.7769 ns/op    0 B/op    0 allocs/op
BenchmarkIsZero/time-12                           1000000000       0.8737 ns/op    0 B/op    0 allocs/op
BenchmarkIsZero/nil-12                            1000000000       0.5586 ns/op    0 B/op    0 allocs/op

PASS
ok      github.com/9ssi7/rapidval       17.819s

Key observations from the benchmarks:

  • Most validation rules have zero allocations
  • Single validations complete in nanoseconds
  • Multiple validations are efficient even with 16 allocations
  • Translation has minimal overhead
  • Zero value checks are extremely fast with no allocations

These benchmarks were run on an Apple M3 Pro processor. Your results may vary depending on your hardware.

Contributing

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

License

See LICENSE for more details.

Documentation

Overview

Package rapidval provides a high-performance, zero-dependency validation library for Go. It focuses on simplicity, extensibility, and performance while providing a clean and intuitive API.

Basic usage:

type User struct {
    Name  string
    Email string
    Age   int
}

func (u *User) Validate(v *rapidval.Validator) error {
    return v.Validate(rapidval.P{
        rapidval.Required("Name", u.Name),
        rapidval.MinLength("Name", u.Name, 2),
        rapidval.Email("Email", u.Email),
        rapidval.Between("Age", u.Age, 18, 100),
    })
}

Index

Constants

View Source
const (
	MsgRequired        = "validation.required"
	MsgInvalidEmail    = "validation.email"
	MsgMinLength       = "validation.min_length"
	MsgMaxLength       = "validation.max_length"
	MsgBetween         = "validation.between"
	MsgDateGreaterThan = "validation.date_greater_than"
	MsgDateLessThan    = "validation.date_less_than"
)

Message Keys

View Source
const (
	Field = "Field"
	Min   = "Min"
	Max   = "Max"
	Value = "Value"
)

MessageParam keys

Variables

This section is empty.

Functions

This section is empty.

Types

type P

type P []*ValidationError

P (Params) is a collection of validation errors used for grouping validations.

type Translator

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

Translator handles the translation of validation error messages. It uses Go's text/template package to support parameterized messages.

func NewTranslator

func NewTranslator() *Translator

NewTranslator creates a new Translator with default messages.

func NewTranslatorWithMessages

func NewTranslatorWithMessages(messages map[string]string) *Translator

NewTranslatorWithMessages creates a new Translator with custom messages. The messages map should use message keys as keys and message templates as values. Message templates can use Go template syntax with .Field, .Min, .Max, and .Value parameters.

func (*Translator) Translate

func (t *Translator) Translate(err *ValidationError) string

Translate converts a ValidationError into a human-readable message using the configured templates. If the message key is not found in the templates, it returns the message key itself.

type Validateable added in v0.0.2

type Validateable interface {

	// Validations is a method that can be implemented by any struct to add custom validation logic.
	// It allows for custom validation logic to be added to a struct without having to implement the Validate method.
	Validations() P
}

Validateable is an interface that can be implemented by any struct to add custom validation logic. It allows for custom validation logic to be added to a struct without having to implement the Validate method.

type ValidationError

type ValidationError struct {
	Field         string
	MessageKey    string
	MessageParams map[string]interface{}
	CurrentValue  interface{}
}

ValidationError represents a single validation error. It contains the field name, message key, and any parameters needed for translation.

func Between

func Between(field string, value int, min, max int) *ValidationError

Between validates if a number is between the specified minimum and maximum values (inclusive).

func DateGreaterThan

func DateGreaterThan(field string, value, min time.Time) *ValidationError

DateGreaterThan validates if a time.Time is after the specified minimum time.

func DateLessThan

func DateLessThan(field string, value, max time.Time) *ValidationError

DateLessThan validates if a time.Time is before the specified maximum time.

func Email

func Email(field string, value string) *ValidationError

Email validates if a string is a valid email address. Currently checks for @ and . characters.

func MaxLength

func MaxLength(field string, value string, max int) *ValidationError

MaxLength validates if a string's length is at most the specified maximum.

func MinLength

func MinLength(field string, value string, min int) *ValidationError

MinLength validates if a string's length is at least the specified minimum.

func Required

func Required(field string, value interface{}) *ValidationError

Required checks if a value is not zero according to its type. For strings, it checks if the string is not empty. For numbers, it checks if the number is not zero. For time.Time, it checks if the time is not zero. For pointers and interfaces, it checks if the value is not nil.

func (*ValidationError) Error

func (ve *ValidationError) Error() string

Error implements the error interface. It returns the message key by default, which can be translated using a Translator.

type ValidationErrors

type ValidationErrors []*ValidationError

ValidationErrors represents a collection of validation errors.

func (ValidationErrors) Error

func (ve ValidationErrors) Error() string

Error implements the error interface. It joins all validation error messages with semicolons.

type Validator

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

Validator handles the validation process and collects validation errors.

func New added in v0.0.2

func New() *Validator

New returns a new Validator.

func (*Validator) Validate

func (v *Validator) Validate(val Validateable) error

Validate processes all validation rules and returns any validation errors. If there are no errors, it returns nil.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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