govalidator

package module
v2.0.5 Latest Latest
Warning

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

Go to latest
Published: May 8, 2024 License: MIT Imports: 10 Imported by: 0

README

Go Reference Go Report Card codecov

GoValidator

GoValidator is a data validation package that can sanitize and validate your data to ensure its safety and integrity as much as possible. GoValidator will not use struct tags as validation and there is no need of them.

Our goal is to avoid using any type assertion or reflection for simplicity. We would be delighted if you were interested in helping us improve the GoValidator package. Feel free to make your pull request.

Getting Started

Go Validator includes a set of validation rules and a handy check() method for defining any custom rule.

Installation

Run the following command to install the package:

go get github.com/rezakhademix/govalidator/v2

Import

Import package in your code-base by using:

import validator "github.com/rezakhademix/govalidator/v2"

Documentation

GoValidator package has the following features and method to use. Each validation rule in GoValidator has it's own default message, e.g: required rule for a required name has the default message of: name is required but you can define your custom field name and message.

Methods (also known as validation rules)

Method Description
RequiredInt RequiredInt checks if an integer value is provided or not.
RequiredFloat RequiredFloat checks if a float value is provided or not.
RequiredString RequiredString checks if a string value is empty or not.
RequiredSlice RequiredSlice checks if a slice has any value or not.
BetweenInt BetweenInt checks whether value falls within the specified range or not.
BetweenFloat BetweenFloat checks whether value falls within the specified range or not.
Date Date checks value to be a valid, non-relative date.
Email Email checks value to match EmailRegex regular expression.
Exists Exists checks given value exists in given table or not.
NotExists NotExists checks given value doesn't exist in given table.
LenString LenString checks length of given string is equal to given size or not.
LenInt LenInt checks length of given integer is equal to given size or not.
LenSlice LenSlice checks length of given slice is equal to given size or not.
MaxInt MaxInt checks given integer is less than or equal given max value.
MaxFloat MaxFloat checks given float is less than or equal given max value.
MaxString MaxString checks length of given string is less than or equal given max value.
MinInt MinInt checks given integer is greater than or equal given min value.
MinFloat MinFloat checks given float is greater than or equal given min value.
MinString MinString checks length of given string is greater than or equal given min value.
RegexMatches RegexMatches checks given string matches given regular expression pattern.
UUID UUID checks given value is a valid universally unique identifier (UUID).
When When will execute given closure if given condition is true.
URL URL will check given string is a valid URL or not.
Before Before will check if given time instant t is before given time instant u.
After After will check if given time instant t is after given time instant u.
IP4 IP4 will check whether given string is a valid IPV4.
DefaultInt DefaultInt sets a default value for any pointer to an int that is passed.
DefaultFloat DefaultFloat sets a default value for any pointer to a float that is passed.
DefaultString DefaultString sets a default value for any pointer to a string that is passed.
Functions (other common validation rules)

Method Description
In In checks given value is included in the provided list of values.
Unique Unique checks whether values in the provided slice are unique.

Examples:

  1. simple:

        type User struct {
            Name string `json:"name"`
            Age unit    `json:"age"`
        }
    
        var user User
        _ := c.Bind(&user)  // error ignored for simplicity
    
        v := govalidator.New()
    
        v.RequiredInt(user.Age, "age", "").         // age can not be null or 0
            MinInt(user.Age, 18, "age", "")         // minimum value for age is 18
    
        v.RequiredString(user.Name, "name", "")     // name can not be null, "" or " "
            MaxString(user.Name, 50, "name", "")    // maximum acceptable length for name field is 50
    
        if v.IsFailed() {
            return v.Errors()  // will return failed validation error messages
        }
    
  2. with custom field names and messages:

        type User struct {
            Name string `json:"name"`
        }
    
        var user User
        _ := c.ShouldBind(&user)  // error ignored for simplicity
    
        v := govalidator.New()
    
        v.MaxString(user.Name, "first_name", "please fill first_name field") // with custom field name and custom validation error message
    
        if v.IsFailed() {
            return v.Errors()
         }
    
  3. more complex with custom validation rule: You can define any custom rules or any flexible rule that does not exist in default govalidator package. Simply use check() method to define your desired data validations:

        type Profile struct {
            Name   string
            Age    int
            Score  int
            Status []string
        }
    
        var profile Profile
    
        // after filling profile struct data with binding or other methods
    
        v := govalidator.New()
    
        v.Check(profile.Name != "", "name", "name is required")  // check is a method to define rule as first parameter and then pass field name and validation error message
    
        v.Check(profile.Age > 18, "age", "age must be greater than 18")
    
        // we just need to pass a bool as a rule
        // `checkScore()` is your custom method that returns a bool and can be used as a rule
        v.Check(checkScore(), "score", "score must")
    
        // using `In` Generic rule:
        statuses := []string{"active", "inactive", "pending"}
    
        v.Check(validator.In[ProfileStatuses](profile.Status, statuses), "status", "status must be in:...")
    
        if v.IsFailed() {
            return v.Errors()
        }
    

Benchmarks

TBD

Documentation

Overview

Package govalidator provides configurable rules for validating data of various types.

Index

Constants

View Source
const (
	// After represents rule name which will be used to find the default error message.
	After = "after"
	// AfterMsg is the default error message format for fields with After validation rule.
	AfterMsg = "%s should be after %v"
)
View Source
const (
	// Before represents rule name which will be used to find the default error message.
	Before = "before"
	// BeforeMsg is the default error message format for fields with Before validation rule.
	BeforeMsg = "%s should be before %v"
)
View Source
const (
	// Between represents rule name which will be used to find the default error message.
	Between = "between"
	// BetweenMsg is the default error message format for fields with Between rule.
	BetweenMsg = "%s should be greater than or equal %v and less than or equal %v"
)
View Source
const (
	// Date represents rule name which will be used to find the default error message.
	Date = "date"
	// DateMsg is the default error message format for fields with Date validation rule.
	DateMsg = "%s has wrong date format"
)
View Source
const (
	// Email represents rule name which will be used to find the default error message.
	Email = "email"
	// EmailMsg is the default error message format for fields with Email validation rule.
	EmailMsg = "%s is not valid"
	// EmailRegex is the default pattern to validate email field by RFC 5322 rule.
	EmailRegex = "" /* 453-byte string literal not displayed */
)
View Source
const (
	// Exists represents rule name which will be used to find the default error message.
	Exists = "exists"
	// ExistsMsg is default error message format for fields with Exists validation rule.
	ExistsMsg = "%s does not exist"
)
View Source
const (
	// IP4 represents rule name which will be used to find the default error message.
	IP4 = "ip4"
	// IP4Msg is the default error message format for fields with IP4 validation rule.
	IP4Msg = "%s should be a valid ipv4"
)
View Source
const (
	// Len represents rule name which will be used to find the default error message.
	Len = "len"
	// LenList represents rule name which will be used to find the default error message.
	LenList = "lenList"
	// LenMsg is the default error message format for fields with Len validation rule.
	LenMsg = "%s should be %d characters"
	// LenListMsg is the default error message format for fields with LenList validation rule.
	LenListMsg = "%s should have %d items"
)
View Source
const (
	// Max represents rule name which will be used to find the default error message.
	Max = "max"
	// MaxString represents rule name which will be used to find the default error message.
	MaxString = "maxString"
	// MaxMsg is the default error message format for fields with Max validation rule.
	MaxMsg = "%s should be less than %v"
	// MaxStringMsg is the default error message format for fields with MaxString validation rule.
	MaxStringMsg = "%s should have less than %v characters"
)
View Source
const (
	// Min represents rule name which will be used to find the default error message.
	Min = "min"
	// MinString represents the rule name which will be used to find the default error message.
	MinString = "minString"
	// MinMsg is the default error message format for fields with Min validation rule.
	MinMsg = "%s should be more than %v"
	// MinStringMsg is the default error message format for fields with MinString validation rule.
	MinStringMsg = "%s should have more than %v characters"
)
View Source
const (
	// NotExists represents rule name which will be used to find the default error message.
	NotExists = "notExists"

	// NotExistsMsg is default error message format for fields with with NotExists validation rule.
	NotExistsMsg = "%s already exists"
)
View Source
const (
	// Regex represents rule name which will be used to find the default error message.
	Regex = "regex"
	// RegexMsg is the default error message format for fields with Regex validation rule.
	RegexMsg = "%s is not valid"
)
View Source
const (
	// Required represents rule name which will be used to find the default error message.
	Required = "required"
	// RequiredMsg is the default error message format for fields with required validation rule.
	RequiredMsg = "%s is required"
)
View Source
const (
	// URL represents rule name which will be used to find the default error message.
	URL = "url"
	// URLMsg is the default error message format for fields with Url validation rule.
	URLMsg = "%s should be a valid url"
)
View Source
const (
	// UUID represents rule name which will be used to find the default error message.
	UUID = "uuid"
	// UUIDMsg is the default error message format for fields with UUID validation rule.
	UUIDMsg = "%s is not a valid UUID"
)

Variables

View Source
var (

	// ErrMethodMessageNotFound is the default message when a method does not have any error message on methodToErrorMessage.
	ErrMethodMessageNotFound = errors.New("method default validation message does not exist in methodToErrorMessage")
)

Functions

func In

func In[T comparable](value T, acceptableValues ...T) bool

In checks if the value under validation must be included in the given list of values.

Example:

result := validator.In("apple", "banana", "orange", "apple")
// result will be true because "apple" is included in the list of acceptable values.

func Unique

func Unique[T comparable](values []T) bool

Unique checks whether the values in the provided slice are unique.

Example:

values := []int{1, 2, 3, 4, 5}
result := validator.Unique(values)
// result will be true because all values in the slice are unique.

Types

type Repository

type Repository interface {
	Exists(value any, table, column string) bool
}

Repository represent a repository for using in rules that needs a database connection to check a record exists on database or not.

type Validator

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

Validator represents the validator structure

func New

func New() Validator

New will return a new validator

func (Validator) After

func (v Validator) After(t, u time.Time, field, msg string) Validator

After checks if given time instant t is after u.

Example:

v := validator.New()

t, _ := time.Parse("2006-01-02", "2009-01-02") // error ignored for simplicity
u, _ := time.Parse("2006-01-02", "2012-01-01") // error ignored for simplicity

v.After(t, u, "birth_date", "birth_date should be after 2012-01-01.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) Before

func (v Validator) Before(t, u time.Time, field, msg string) Validator

Before checks if given time instant t is before u.

Example:

v := validator.New()

t, _ := time.Parse("2006-01-02", "2009-01-02") // error ignored for simplicity
u, _ := time.Parse("2006-01-02", "2012-01-01") // error ignored for simplicity

v.Before(t, u, "birth_date", "birth_date should be before 2012-01-01.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) BetweenFloat

func (v Validator) BetweenFloat(f, min, max float64, field, msg string) Validator

BetweenFloat checks the field under validation to have a float value between the given min and max.

Example:

v := validator.New()
v.BetweenFloat(3.5, 2.0, 5.0, "height", "height must be between 2.0 and 5.0 meters.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) BetweenInt

func (v Validator) BetweenInt(i, min, max int, field, msg string) Validator

BetweenInt checks the value under validation to have an integer value between the given min and max.

Example:

v := validator.New()
v.BetweenInt(21, 1, 10, "age", "age must be between 1 and 10.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) Check

func (v Validator) Check(ok bool, field, msg string)

Check is a dynamic method to define any custom validator rule by passing a rule as a function or expression which will return a boolean.

func (Validator) Date

func (v Validator) Date(layout, d, field, msg string) Validator

Date checks the value under validation to be a valid, non-relative date with give layout.

Example:

v := validator.New()
v.Date("2006-01-02", "2024-03-09","birthdate", "birthdate must be a valid date in the format YYYY-MM-DD.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) DefaultFloat added in v2.0.3

func (v Validator) DefaultFloat(f *float64, val float64) Validator

DefaultFloat sets a default value for any pointer to a float that is passed if value does not exist, will set the default specified as the new value.

Example:

v := validator.New()
var f float64
v.DefaultFloat(&f, 3.14)

func (Validator) DefaultInt added in v2.0.3

func (v Validator) DefaultInt(i *int, val int) Validator

DefaultInt sets a default value for any pointer to an int that is passed if value does not exist, will set the default specified as the new value.

Example:

v := validator.New()
var zeroKelvin int64
v.DefaultInt(&zeroKelvin, -273)

func (Validator) DefaultString added in v2.0.3

func (v Validator) DefaultString(s *string, val string) Validator

DefaultString sets a default value for any pointer to a string that is passed. if value does not exist, will set the default specified as the new value.

Example:

v := validator.New()
var lang string
v.DefaultString(&lang, "persian")

func (Validator) Email

func (v Validator) Email(s, field, msg string) Validator

Email checks the value under validation must match the EmailRegex regular expression.

Example:

v := validator.New()
v.Email("john.doe@example.com", "email", "email address is not valid.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) Errors

func (v Validator) Errors() map[string]string

Errors returns a map of all validator rule errors.

func (Validator) Exists

func (v Validator) Exists(value any, table, column, field, msg string) Validator

Exists checks if given value exists in the desired table or not.

Example:

v := validator.New()
v.Exists(42, "users", "id", "user_id", "user with id 42 does not exist.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) IP4

func (v Validator) IP4(s, field, msg string) Validator

IP4 checks if given string is a valid IPV4.

Example:

v := validator.New()
v.IP4("127.0.0.1", "server_ip", "server_ip should be a valid ipv4.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) IsFailed

func (v Validator) IsFailed() bool

IsFailed checks if the validator result has failed or not.

func (Validator) IsPassed

func (v Validator) IsPassed() bool

IsPassed checks if the validator result has passed or not.

func (Validator) LenInt

func (v Validator) LenInt(i, size int, field, msg string) Validator

LenInt checks if the length of the given integer is equal to the given size or not.

Example:

v := validator.New()
v.LenInt(12345, 5, "zipcode", "Zip code must be 5 digits long.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) LenSlice

func (v Validator) LenSlice(s []any, size int, field, msg string) Validator

LenSlice checks if the length of the given slice is equal to the given size or not.

Example:

v := validator.New()
v.LenSlice([]int{1, 2, 3, 4, 5}, 5, "numbers", "the list must contain exactly 5 numbers.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) LenString

func (v Validator) LenString(s string, size int, field, msg string) Validator

LenString checks if the length of a string is equal to the given size or not.

Example:

v := validator.New()
v.LenString("rez", 5, "username", "username must be 5 characters.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) MaxFloat

func (v Validator) MaxFloat(f, max float64, field, msg string) Validator

MaxFloat checks if the given float value is less than or equal the given max value.

Example:

v := validator.New()
v.MaxFloat(3.5, 5.0, "height", "height must be less than 5.0 meters.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) MaxInt

func (v Validator) MaxInt(i, max int, field, msg string) Validator

MaxInt checks if the integer value is less than or equal the given max value.

Example:

v := validator.New()
v.MaxInt(10, 100, "age", "age must be less than 100.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) MaxString

func (v Validator) MaxString(s string, maxLen int, field, msg string) Validator

MaxString checks if the length of given string is less than or equal the given max value.

Example:

v := validator.New()
v.MaxString("rey", 5, "name", "name should have less than 5 characters.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) MinFloat

func (v Validator) MinFloat(f, min float64, field, msg string) Validator

MinFloat checks if the given float value is greater than or equal the given min value.

Example:

v := validator.New()
v.MinFloat(5.0, 0.0, "height", "height must be at least 0.0 meters.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) MinInt

func (v Validator) MinInt(i, min int, field, msg string) Validator

MinInt checks if the given integer value is greater than or equal the given min value.

Example:

v := validator.New()
v.MinInt(18, 0, "age", "age must be at least 0.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) MinString

func (v Validator) MinString(s string, minLen int, field, msg string) Validator

MinString checks if the length of given string is greater than or equal the given min value.

Example:

v := validator.New()
v.MinString("rey", 5, "name", "name should have more than 5 characters.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) NotExists

func (v Validator) NotExists(value any, table, column, field, msg string) Validator

NotExists checks if the given value doesn't exist in the desired table.

Example:

v := validator.New()
v.NotExists(42, "users", "id", "user_id", "user with id 42 already exists.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) RegexMatches

func (v Validator) RegexMatches(s string, pattern string, field, msg string) Validator

RegexMatches checks if the given value of s under validation matches the given regular expression pattern.

Example:

v := validator.New()
v.RegexMatches("example123", "[a-z]+[0-9]+", "input", "input must contain letters followed by numbers.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) RequiredFloat

func (v Validator) RequiredFloat(f float64, field string, msg string) Validator

RequiredFloat checks if a float value is provided or not.

Example:

v := validator.New()
v.RequiredFloat(3.5, "weight", "weight is required.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) RequiredInt

func (v Validator) RequiredInt(i int, field string, msg string) Validator

RequiredInt checks if an integer value is provided or not.

Example:

v := validator.New()
v.RequiredInt(42, "age", "age is required.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) RequiredSlice

func (v Validator) RequiredSlice(s []any, field string, msg string) Validator

RequiredSlice checks if a slice has any value or not.

Example:

v := validator.New()
v.RequiredSlice([]string{"apple", "banana", "orange"}, "fruits", "at least one fruit must be provided.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) RequiredString

func (v Validator) RequiredString(s, field string, msg string) Validator

RequiredString checks if a string value is empty or not.

Example:

v := validator.New()
v.RequiredString("hello", "username", "username is required.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) URL

func (v Validator) URL(s, field, msg string) Validator

URL checks if a string value is a valid url or not.

Example:

v := validator.New()
v.URL("https://go.dev/play", "path", "path should be a valid url.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) UUID

func (v Validator) UUID(u, field, msg string) Validator

UUID validates that the field under validation is a valid RFC 4122 universally unique identifier (UUID). It accepts non-standard strings such as raw hex encoding xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx and 38 byte "Microsoft style" encodings, e.g., {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}.

Example:

v := validator.New()
v.UUID("f47ac10b-58cc-4372-a567-0e02b2c3d479", "uuid", "Invalid UUID format.")
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) When

func (v Validator) When(condition bool, f func()) Validator

When method will execute the given closure if the given condition is true.

Example:

v := validator.New()
v.When(len(username) > 0, func() {
    validator.RequiredString(username, "username", "username is required.")
})
if v.IsFailed() {
	 fmt.Printf("validation errors: %#v\n", v.Errors())
}

func (Validator) WithRepo

func (v Validator) WithRepo(r Repository) Validator

WithRepo sets the desired repository for use in the Exists validation rule.

Example:

validator := New().WithRepo(myRepository)

Jump to

Keyboard shortcuts

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