
validator
A simple validation utility for collecting and managing validation errors. Supports boolean and error-based validation with formatted error messages.
Installation
go get github.com/LightArrayCapital/go-utilities/validator
Forked from moonrhythm/validator.
Usage
The validator package provides a Validator type that collects validation errors and allows you to check if all validations passed.
Basic Example
package main
import (
"fmt"
"github.com/LightArrayCapital/go-utilities/validator"
)
func validateUser(name string, age int) error {
v := validator.New()
// Validate name is not empty
v.Must(name != "", "name is required")
// Validate age is positive
v.Must(age > 0, "age must be positive")
// Validate age is reasonable
v.Mustf(age < 150, "age %d is too large", age)
// Return combined error if any validation failed
return v.Error()
}
func main() {
if err := validateUser("", -5); err != nil {
fmt.Println("Validation failed:", err)
}
}
Using with Errors
func validateData(data string) error {
v := validator.New()
// Check if a function returns an error
if err := someValidation(data); err != nil {
v.Must(err, "error during someValidation") // Add the error directly
}
// Or use Must with the error directly
v.Must(anotherValidation(data), "")
return v.Error()
}
Checking Validation Status
v := validator.New()
v.Must(len(username) >= 3, "username must be at least 3 characters")
v.Must(email != "", "email is required")
if !v.Valid() {
// Handle validation errors
return v.Error()
}