okay

package module
v0.0.0-...-651c464 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2023 License: Apache-2.0 Imports: 2 Imported by: 4

README

Go Reference

ugent-library/okay

Simple validation for Go.

Install

go get -u github.com/ugent-library/okay

Examples

Sugared validation:

func Validate(u *User) error {
	return okay.Validate(
		okay.NotEmpty("username", f.Username),
		okay.LengthBetween("username", f.Username, 1, 100),
        // with custom message
		okay.LengthBetween("username", f.Username, 1, 100).WithMessage("Username is too short or too long"),
	)
}

Building validation errors manually:

func Validate(r *Rec) error {
    errs := okay.NewErrors()
    for i, link := range r.Links
        if isExpired(link) {
            errs.Add(okay.NewError(fmt.Sprintf("/rec/links/%d", i), "link.expired"))
        }
    }
    return errs.ErrorOrNil()
}

Rules and parameters:

err := okay.LengthBetween("username", f.Username, 1, 100)
msg := fmt.Sprintf("%s should have %s %d and %d", err.Key, err.Rule, err.Params...)
// msg is "username should have length_between 1 and 100"

I18n:

import "github.com/leonelquinteros/gotext"

func ErrorMessages(loc *gotext.Locale, errs *okay.Errors) msgs []string {
    for _, err := range errs.Errors {
        msgs = append(msgs, loc.Get(err.Rule, err.Params...))
    }
    return
}

Documentation

Index

Constants

View Source
const (
	RuleNotEmpty      = "not_empty"
	RuleLength        = "length"
	RuleLengthBetween = "length_between"
	RuleMin           = "min"
	RuleMax           = "max"
	RuleMatch         = "match"
	RuleAlphanumeric  = "alphanumeric"
	RuleUnique        = "unique"
)

Variables

View Source
var (
	MessageNotEmpty     = "cannot be empty"
	MessageLength       = "length must be %d"
	MessageLengthIn     = "length must be between %d and %d"
	MessageMin          = "must be %d or more"
	MessageMax          = "must be %d or less"
	MessageMatch        = "must match %s"
	MessageAlphanumeric = "must only contain letters a to z and digits"
	MessageUnique       = "must be unique"

	ReAlphanumeric = regexp.MustCompile("^[a-zA-Z0-9]+$")
)

Functions

func Add

func Add(err error, errs ...error) error

Add is a convenience function to add zero or more validation errors to an Errors.

If err is nil, a new Errors wil be created and returned. If the given validation error is an Errors, it's validation errors will be added to err.

If err is not an Errors or the given validation errors are not an Errors or an Error, the function will panic.

func Validate

func Validate(errs ...error) error

Add is a convenience function to create an Errors and add zero or more validation errors. Returns nil if there are no errors.

Types

type Error

type Error struct {
	Key     string
	Rule    string
	Params  []any
	Message string
}

func Alphanumeric

func Alphanumeric(key, val string) *Error

Alphanumeric checks if a given string only contains letters a to z, letters A to Z or digits.

err := okay.Match("issn", "1940-5758", regexp.MustCompile(`^[0-9]{4}-[0-9]{3}[0-9X]$`))

func ErrNotUnique

func ErrNotUnique(key string) *Error

ErrNotUnique is a convenience function to signal that a given key fails a uniqueness test.

func Length

func Length[T ~string | ~[]any | ~map[any]any](key string, val T, n int) *Error

Length checks if the given string, slice or map has a given length.

err := okay.Length("keywords", []string{"childcare"}, 1)

func LengthBetween

func LengthBetween[T ~string | ~[]any | ~map[any]any](key string, val T, min, max int) *Error

LengthBetween checks if the given string, slice or map has a length that is greater than or equal to min and less than or equal to max.

err := okay.Length("keywords", []string{"childcare"}, 0, 10)

func Match

func Match(key, val string, r *regexp.Regexp) *Error

Match checks if the given string matches a regular expression.

err := okay.Match("issn", "1940-5758", regexp.MustCompile(`^[0-9]{4}-[0-9]{3}[0-9X]$`))

func Max

func Max[T int | int64 | float64](key string, val T, max T) *Error

Max checks if the given string, slice or map has a length that is less than or equal to max.

err := okay.Max("keywords", []string{"childcare"}, 10)

func Min

func Min[T int | int64 | float64](key string, val T, min T) *Error

Min checks if the given string, slice or map has a length that is greater than or equal to min.

err := okay.Min("keywords", []string{"childcare", "education"}, 1)

func NewError

func NewError(key, rule string, params ...any) *Error

NewError constructs a new validation error. key represents the field or value that failed validation. There are no assumptions about the nature of this key, it could be a JSON pointer or the name of a (nested) form field.

func NotEmpty

func NotEmpty[T ~string | ~[]any | ~map[any]any](key string, val T) *Error

NotEmpty checks if the given string, slice or map is not empty.

err := okay.NotEmpty("keywords", []string{"childcare"})

func (*Error) Error

func (e *Error) Error() string

Error returns a string representation of the validation error.

func (*Error) WithMessage

func (e *Error) WithMessage(msg string) *Error

WithMessage sets a custom error message if the validation error is not nil.

type Errors

type Errors struct {
	Errors []*Error
}

func NewErrors

func NewErrors(errs ...*Error) *Errors

NewErrors constructs a new Errors with the given validation errors.

func (*Errors) Add

func (e *Errors) Add(errs ...*Error) *Errors

Add zero or more validation errors.

func (*Errors) Error

func (e *Errors) Error() string

Error returns a string representation of an Errors.

func (*Errors) ErrorOrNil

func (e *Errors) ErrorOrNil() error

ErrorOrNil returns Errors as a (nil) error interface value.

func (*Errors) Get

func (e *Errors) Get(key string) *Error

Get fetches an Error by key or return nil if the key is not found.

Jump to

Keyboard shortcuts

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