validator

package
v0.0.0-...-75af99c Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2023 License: BSD-2-Clause Imports: 7 Imported by: 0

Documentation

Overview

Package validator provides struct validation based on tags.

Example
package main

import (
	"fmt"

	"github.com/n4x2/zoo/validator"
)

type Student struct {
	FName  string `json:"first_name" v:"lowercase"`
	MName  string `json:"middle_name" v:"-|lowercase"`
	LName  string `json:"last_name" v:"lowercase"`
	Age    int8   `v:"lt:18"`
	Gender string `json:"gender" v:"enum:female,male"`
}

func main() {
	var s = Student{
		FName:  "John",
		LName:  "doe",
		Age:    18,
		Gender: "male",
	}

	v := validator.New()
	validation, err := v.ValidateStruct(s)
	if err != nil {
		panic(err)
	}

	fmt.Print(validation)
}
Output:

[{first_name [must be lowercase characters]} {Age [must be less than 18]}]

Index

Examples

Constants

View Source
const (
	ValidatorTag = "v"    // Default validator tag.
	SkipTag      = "-"    // Default tag to skip validation.
	JSONTag      = "json" // Default JSON tag.
	PairSep      = ":"    // Default pair separator.
	ParamSep     = ","    // Default parameter separator.
	TagSep       = "|"    // Default tag separator.
)

Default values for validation.

View Source
const (
	NameIndex  = 0 // Index for tag name.
	ParamIndex = 1 // Index for tag parameter.
)

Index for tag parsing.

Variables

View Source
var E = map[string]string{
	"alpha":     "must be alphabetic characters",
	"alphadash": "must be alphaNeric characters, dash, and underscore",
	"alphanum":  "must be alphanumeric characters",
	"ascii":     "must be ASCII characters",
	"enum":      "%v not allowed for this field",
	"email":     "invalid email address",
	"equal":     "must be the same as %v",
	"gt":        "must be greater than %v",
	"gte":       "must be greater than or equal to %v",
	"lat":       "invalid latitude: %v",
	"lon":       "invalid longitude: %v",
	"lt":        "must be less than %v",
	"lte":       "must be less than or equal to %v",
	"lowercase": "must be lowercase characters",
	"range":     "value must be in range %v-%v",
	"ulid":      "invalid ULID",
	"uuid":      "invalid UUID",
	"uppercase": "must be uppercase characters",
}

E store associates error messages with specific validation rules.

View Source
var R = map[string]Detail{
	"alpha":     {Fn: is.Alpha, Maxp: 0, N: false},
	"alphadash": {Fn: is.AlphaDash, Maxp: 0, N: false},
	"alphanum":  {Fn: is.AlphaNumeric, Maxp: 1, N: false},
	"ascii":     {Fn: is.ASCII, Maxp: 0, N: false},
	"enum":      {Fn: is.Contain[[]string, string], Maxp: -1, N: false},
	"email":     {Fn: is.Email, Maxp: 0, N: false},
	"equal":     {Fn: is.Equal[float64], Maxp: 1, N: true},
	"gt":        {Fn: is.GreaterThan[float64], Maxp: 1, N: true},
	"gte":       {Fn: is.GreaterThanEqual[float64], Maxp: 1, N: true},
	"lat":       {Fn: is.Latitude, Maxp: 0, N: false},
	"lon":       {Fn: is.Longitude, Maxp: 0, N: false},
	"lt":        {Fn: is.LessThan[float64], Maxp: 1, N: true},
	"lte":       {Fn: is.LessThanEqual[float64], Maxp: 1, N: true},
	"lowercase": {Fn: is.Lowercase, Maxp: 0, N: false},
	"range":     {Fn: is.Range[float64], Maxp: 2, N: true},
	"ulid":      {Fn: is.ULID, Maxp: 0, N: false},
	"uuid":      {Fn: is.UUID, Maxp: 0, N: false},
	"uppercase": {Fn: is.Uppercase, Maxp: 0, N: false},
}

R stores default validation tags, it wraps functions from the is package to perform validation.

Functions

This section is empty.

Types

type Detail

type Detail struct {
	Fn   any  // Function for validation.
	Maxp int  // Maximum allowed parameter.
	N    bool // Set 'true' if tag processing numerical value.
}

Detail holds the tag validation details.

type Field

type Field struct {
	N string // The field name.
	V any    // The field value.
	T []Tag  // Validation tags.
}

Field represents fields data containing name, value, and associated validation tags.

type Result

type Result struct {
	F string   // The field name.
	E []string // Error messages.
}

Result represents a validation error, including the field name and error messages.

type Tag

type Tag struct {
	N string // The tag name.
	P []any  // Optional parameters.
}

Tag represents a validation tag, including tag name and optional parameters.

type Validator

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

Validator contains default error messages and validation rules.

func New

func New() *Validator

New creates new validator instances.

func (*Validator) AddRuleNumeric

func (r *Validator) AddRuleNumeric(n string, fn func(float64, float64) error, maxp int) error

AddRuleNumeric add custom rule that processing numeric values into validator. It need 'n' tag name, 'fn' function that perform validation, and 'maxp' to determine maximum allowed parameter. It returns an error if tag name already exists.

Example
package main

import (
	"fmt"

	"github.com/n4x2/zoo/validator"
)

func NotEqual(val, param float64) error {
	if val == param {
		return fmt.Errorf("must be equal %v", param)
	}

	return nil
}

type Expire struct {
	Year int `json:"expire_year" v:"notequal:2017"`
}

func main() {
	var b = Expire{
		Year: 2017,
	}

	v := validator.New()
	err := v.AddRuleNumeric("notequal", NotEqual, 1)
	if err != nil {
		panic(err)
	}

	result, err := v.ValidateStruct(b)
	if err != nil {
		panic(err)
	}

	fmt.Println(result)
}
Output:

[{expire_year [must be equal 2017]}]

func (*Validator) AddRuleString

func (r *Validator) AddRuleString(n string, fn func(string) error) error

AddRuleString add custom rule that processing string values into validator. It require 'n' tag name and 'fn' function that perform validation as input. It returns an error if tag name already exists.

Example
package main

import (
	"errors"
	"fmt"
	"regexp"

	"github.com/n4x2/zoo/validator"
)

func StartCase(val string) error {
	pattern := `^([A-Z][a-z]*)+(\s[A-Z][a-z]*)*$`
	regex := regexp.MustCompile(pattern)

	if regex.MatchString(val) {
		return nil
	}

	return errors.New("must be start case")
}

type Book struct {
	Title string `json:"book_title" v:"startcases"`
}

func main() {
	var b = Book{
		Title: "how To make Money",
	}

	v := validator.New()
	err := v.AddRuleString("startcases", StartCase)
	if err != nil {
		panic(err)
	}

	result, err := v.ValidateStruct(b)
	if err != nil {
		panic(err)
	}

	fmt.Println(result)
}
Output:

[{book_title [must be start case]}]

func (*Validator) ValidateField

func (r *Validator) ValidateField(v any, st []Tag) ([]string, error)

ValidateField validate given value based on tags. It returns slices of validation messages if any validation error encountered. It returns an error if rule is not found or type conversion is failed.

func (*Validator) ValidateStruct

func (r *Validator) ValidateStruct(v any) ([]Result, error)

ValidateStruct validate given struct based on their associated tags. It will returns slices of Result containing field name and error messages if any validation error encountered. It returns an error if input is not struct or failed to parse fields or failed to convert values.

Jump to

Keyboard shortcuts

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