validate

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 6, 2025 License: GPL-3.0 Imports: 8 Imported by: 3

README

go-validate

Validations for struct fields based on a validation tag and offers additional validation functions

Release Build Status Report codecov Go Sponsor Donate


Table of Contents


Installation

go-validate requires a supported release of Go.

go get -u github.com/mrz1836/go-validate

Documentation

View the generated documentation

GoDoc

Library Deployment

goreleaser for easy binary or library deployment to GitHub and can be installed via: brew install goreleaser.

The .goreleaser.yml file is used to configure goreleaser.

Use make release-snap to create a snapshot version of the release, and finally make release to ship to production.

Makefile Commands

View all makefile commands

make help

List of all current commands:

all                  Runs multiple commands
clean                Remove previous builds and any test cache data
clean-mods           Remove all the Go mod cache
coverage             Shows the test coverage
godocs               Sync the latest tag with GoDocs
help                 Show this help message
install              Install the application
install-go           Install the application (Using Native Go)
lint                 Run the golangci-lint application (install if not found)
release              Full production release (creates release in Github)
release              Runs common.release then runs godocs
release-snap         Test the full release (build binaries)
release-test         Full production test release (everything except deploy)
replace-version      Replaces the version in HTML/JS (pre-deploy)
run-examples         Runs all the examples
tag                  Generate a new tag and push (tag version=0.0.0)
tag-remove           Remove a tag if found (tag-remove version=0.0.0)
tag-update           Update an existing tag to current commit (tag-update version=0.0.0)
test                 Runs vet, lint and ALL tests
test-ci              Runs all tests via CI (exports coverage)
test-ci-no-race      Runs all tests via CI (no race) (exports coverage)
test-ci-short        Runs unit tests via CI (exports coverage)
test-short           Runs vet, lint and tests (excludes integration tests)
uninstall            Uninstall the application (and remove files)
update-linter        Update the golangci-lint package (macOS only)
vet                  Run the Go vet application

Examples & Tests

All unit tests and examples run via GitHub Actions and use Go version 1.15.x. View the configuration file.

Run all tests (including integration tests)

make test

Run tests (excluding integration tests)

make test-short

Benchmarks

Run the Go benchmarks:

make bench

Code Standards

Read more about this Go project's code standards.


Usage

Basic model implementation:

// ExampleModel shows inline validations via the struct tag
type ExampleModel struct {
    Age             uint    `validation:"min=18"`
    Category        string  `validation:"min_length=5 max_length=10"`
    Email           string  `validation:"format=email"`
    Name            string  `validation:"format=regexp:[A-Z][a-z]{3,12}"`
    Password        string  `validation:"compare=PasswordConfirm"`
    PasswordConfirm string  `json:"-"`
    Quantity        uint    `validation:"min=1 max=5"`
    Total           float32 `validation:"min=0"`
}

// Example showing extra validation functions for additional use
ok, err := validate.IsValidEmail("someones@email.com")
if !ok {
    errs = append(errs, validate.ValidationError{
        Key:     "Email",
        Message: err.Error(),
    })
}

Maintainers

MrZ kayleg
MrZ kayleg

Contributing

View the contributing guidelines and follow the code of conduct.

How can I help?

All kinds of contributions are welcome 🙌! The most basic way to show your support is to star 🌟 the project, or to raise issues 💬. You can also support this project by becoming a sponsor on GitHub 👏 or by making a bitcoin donation to ensure this journey continues indefinitely! 🚀


License

License

Documentation

Overview

Package validate (go-validate) provides validations for struct fields based on a validation tag and offers additional validation functions.

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultMap = Map{}

DefaultMap is the default validation map used to tell if a struct is valid.

Functions

func AddValidation

func AddValidation(key string, fn func(string, reflect.Kind) (Interface, error))

AddValidation registers the validation specified by a key to the known validations. If more than one validation registers with the same key, the last one will become the validation for that key using DefaultMap.

func IsValidDNSName added in v0.1.7

func IsValidDNSName(dnsName string) bool

IsValidDNSName will validate the given string as a DNS name

Example (Invalid)

ExampleIsValidDNSName_invalid example of an invalid dns name

ok := IsValidDNSName("localhost.-localdomain")
fmt.Println(ok)
Output:

false
Example (Valid)

ExampleIsValidDNSName_valid example of a valid dns name

ok := IsValidDNSName("localhost")
fmt.Println(ok)
Output:

true

func IsValidEmail added in v0.1.1

func IsValidEmail(email string, mxCheck bool) (success bool, err error)

IsValidEmail validate an email address using regex, checking name and host, and even MX record check

Example (Invalid)

ExampleIsValidEmail_invalid example of an invalid email address response

ok, err := IsValidEmail("notvalid@domain", false) // Invalid
fmt.Println(ok, err)
Output:

false email is not a valid address format
Example (Valid)

ExampleIsValidEmail_valid example of a valid email address response

ok, err := IsValidEmail("person@gmail.com", false) // Valid
fmt.Println(ok, err)
Output:

true <nil>

func IsValidEnum added in v0.1.1

func IsValidEnum(enum string, allowedValues *[]string, emptyValueAllowed bool) (success bool, err error)

IsValidEnum validates an enum given the required parameters and tests if the supplied value is valid from accepted values

Example (Invalid)

ExampleIsValidEnum_invalid example of an invalid enum

testAcceptedValues := []string{"123"}
ok, err := IsValidEnum("1", &testAcceptedValues, false) // Invalid
fmt.Println(ok, err)
Output:

false value 1 is not allowed
Example (Valid)

ExampleIsValidEnum_valid example of an valid enum

testAcceptedValues := []string{"123"}
ok, err := IsValidEnum("123", &testAcceptedValues, false) // Valid
fmt.Println(ok, err)
Output:

true <nil>

func IsValidHost added in v0.1.7

func IsValidHost(host string) bool

IsValidHost checks if the string is a valid IP (both v4 and v6) or a valid DNS name

Example (Invalid)

ExampleIsValidHost_invalid example of an invalid host

ok := IsValidHost("-localhost")
fmt.Println(ok)
Output:

false
Example (Valid)

ExampleIsValidHost_valid example of a valid host

ok := IsValidHost("localhost")
fmt.Println(ok)
Output:

true

func IsValidIP added in v0.1.7

func IsValidIP(ipAddress string) bool

IsValidIP checks if a string is either IP version 4 or 6. Alias for `net.ParseIP`

Example (Invalid)

ExampleIsValidIP_invalid example of an invalid ip address

ok := IsValidIP("300.0.0.0")
fmt.Println(ok)
Output:

false
Example (Valid)

ExampleIsValidIP_valid example of a valid ip address

ok := IsValidIP("127.0.0.1")
fmt.Println(ok)
Output:

true

func IsValidIPv4 added in v0.1.7

func IsValidIPv4(ipAddress string) bool

IsValidIPv4 check if the string is IP version 4.

func IsValidIPv6 added in v0.1.7

func IsValidIPv6(ipAddress string) bool

IsValidIPv6 check if the string is IP version 6.

func IsValidPhoneNumber added in v0.1.2

func IsValidPhoneNumber(phone string, countryCode string) (success bool, err error)

IsValidPhoneNumber validates a given phone number and country code

Example (Invalid)

ExampleIsValidPhoneNumber_invalid example of an invalid phone number

countryCode := "+1"
phone := "555-444-44"
ok, err := IsValidPhoneNumber(phone, countryCode)
fmt.Println(ok, err)
Output:

false phone number must be ten digits
Example (Valid)

ExampleIsValidPhoneNumber_valid example of a valid phone number

countryCode := "+1"
ok, err := IsValidPhoneNumber(testPhone, countryCode)
fmt.Println(ok, err)
Output:

true <nil>

func IsValidSocial added in v0.1.1

func IsValidSocial(social string) (success bool, err error)

IsValidSocial validates the USA social security number using ATS rules

Example (Invalid)

ExampleIsValidSocial_invalid example of an invalid social response

ok, err := IsValidSocial("666-00-0000") // Invalid
fmt.Println(ok, err)
Output:

false social section was found invalid (cannot be 000 or 666)
Example (Valid)

ExampleIsValidSocial_invalid example of a valid social response

ok, err := IsValidSocial("212126768") // Valid
fmt.Println(ok, err)
Output:

true <nil>

Types

type Interface

type Interface interface {

	// SetFieldIndex stores the index of the field
	SetFieldIndex(index int)

	// FieldIndex retrieves the index of the field
	FieldIndex() int

	// SetFieldName stores the name of the field
	SetFieldName(name string)

	// FieldName retrieves the name of the field
	FieldName() string

	// Validate determines if the value is valid. The value nil is returned if it is valid
	Validate(value interface{}, obj reflect.Value) *ValidationError
}

Interface specifies the necessary methods a validation must implement to be compatible with this package

type Map

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

Map is an atomic validation map, and when two sets happen at the same time, the latest that started wins.

func (*Map) AddValidation

func (m *Map) AddValidation(key string, fn func(string, reflect.Kind) (Interface, error))

AddValidation registers the validation specified by a key to the known validations. If more than one validation registers with the same key, the last one will become the validation for that key.

func (*Map) IsValid

func (m *Map) IsValid(object interface{}) (bool, []ValidationError)

IsValid will either store the builder interfaces or run the IsValid based on the reflection object type

type Validation

type Validation struct {

	// Name of the validation
	Name string
	// contains filtered or unexported fields
}

Validation is an implementation of an Interface and can be used to provide basic functionality to a new validation type through an anonymous field

func (*Validation) FieldIndex

func (v *Validation) FieldIndex() int

FieldIndex retrieves the index of the field the validation was applied to

func (*Validation) FieldName

func (v *Validation) FieldName() string

FieldName retrieves the name of the field the validation was applied to

func (*Validation) SetFieldIndex

func (v *Validation) SetFieldIndex(index int)

SetFieldIndex stores the index of the field the validation was applied to

func (*Validation) SetFieldName

func (v *Validation) SetFieldName(name string)

SetFieldName stores the name of the field the validation was applied to

func (*Validation) Validate

func (v *Validation) Validate(_ interface{}, _ reflect.Value) *ValidationError

Validate determines if the value is valid. The value nil is returned if it is valid

type ValidationError

type ValidationError struct {

	// Key is the Field name, key name
	Key string

	// Message is the error message
	Message string
}

ValidationError is the key and message of the corresponding error

func IsValid

func IsValid(object interface{}) (bool, []ValidationError)

IsValid determines if an object is valid based on its validation tags using DefaultMap.

Example (CompareString)

ExampleIsValid_CompareString is an example for compare string validation

type User struct {
	// Password should match confirmation on submission
	Password             string `validation:"compare=PasswordConfirmation"`
	PasswordConfirmation string
}

var u User // User submits a new password and confirms wrong
u.Password = "This"
u.PasswordConfirmation = "That"

ok, errs := IsValid(u)
fmt.Println(ok, errs)
Output:

false [{Password is not the same as the compare field PasswordConfirmation}]
Example (FormatEmail)

ExampleIsValid_FormatEmail is an example for format email validation

type Person struct {
	// Email must be in valid email format
	Email string `validation:"format=email"`
}

var p Person
// Will fail since the email is not valid

ok, errs := IsValid(p)
fmt.Println(ok, errs)
Output:

false [{Email does not match email format}]
Example (FormatRegEx)

ExampleIsValid_FormatRegEx is an example for format regex validation

type Person struct {
	// Phone must be in valid phone regex format
	Phone string `validation:"format=regexp:[0-9]+"`
}

var p Person
// Will fail since the email is not valid

ok, errs := IsValid(p)
fmt.Println(ok, errs)
Output:

false [{Phone does not match regexp format}]
Example (MaxFloat)

ExampleIsValid_MaxFloat is an example for Float Value validation (max)

type Product struct {
	// Price must more than 0.01 but less than 999.99
	Price float32 `validation:"min=0.01 max=999.99"`
}

var p Product
p.Price = 10000.00 // Will fail since it's greater than 999.99

ok, errs := IsValid(p)
fmt.Println(ok, errs)
Output:

false [{Price must be less than or equal to 9.9999E+02}]
Example (MaxInt)

ExampleIsValid_MaxInt is an example for Int Value validation (max)

type Product struct {
	// Quantity must more than 1 but less than 99
	Quantity int8 `validation:"min=1 max=99"`
}

var p Product
p.Quantity = 101 // Will fail since it's greater than 99

ok, errs := IsValid(p)
fmt.Println(ok, errs)
Output:

false [{Quantity must be less than or equal to 99}]
Example (MaxLength)

ExampleIsValid_MaxLength is an example for max length validation (max)

type Person struct {
	// Gender must not be longer than 10 characters
	Gender string `validation:"max_length=10"`
}

var p Person
p.Gender = "This is invalid!" // Will fail since it's > 10 characters

ok, errs := IsValid(p)
fmt.Println(ok, errs)
Output:

false [{Gender must be no more than 10 characters}]
Example (MinFloat)

ExampleIsValid_MinFloat is an example for Float Value validation (min)

type Product struct {
	// Price must more than 0.01
	Price float32 `validation:"min=0.01"`
}

var p Product
// Will fail since its Price = 0

ok, errs := IsValid(p)
fmt.Println(ok, errs)
Output:

false [{Price must be greater than or equal to 1E-02}]
Example (MinInt)

ExampleIsValid_MinInt is an example for Int Value validation (min)

type Product struct {
	// Quantity must more than 1
	Quantity int8 `validation:"min=1"`
}

var p Product
// Will fail since its Quantity = 0

ok, errs := IsValid(p)
fmt.Println(ok, errs)
Output:

false [{Quantity must be greater than or equal to 1}]
Example (MinLength)

ExampleIsValid_MinLength is an example for min length validation (min)

type Person struct {
	// Gender must be > 1 character
	Gender string `validation:"min_length=1"`
}

var p Person
// Will fail since it's < 1 character

ok, errs := IsValid(p)
fmt.Println(ok, errs)
Output:

false [{Gender must be at least 1 characters}]

func (*ValidationError) Error

func (v *ValidationError) Error() string

ValidationError returns a string of a key + a message

Example

ExampleValidationError_Error is showing how to use the errors

type Person struct {
	// Gender must not be longer than 10 characters
	Gender string `validation:"max_length=10"`
}

var p Person
p.Gender = "This is invalid!" // Will fail since it's > 10 characters

_, errs := IsValid(p)
fmt.Println(errs[0].Error())
Output:

Gender must be no more than 10 characters

type ValidationErrors

type ValidationErrors []ValidationError

ValidationErrors is a slice of validation errors

func (ValidationErrors) Error

func (v ValidationErrors) Error() (errors string)

ValidationError returns the list of errors from the slice of errors

Directories

Path Synopsis
examples
model command
Package main is an example of using the "validate package" in a basic model (validating data before persisting into a database)
Package main is an example of using the "validate package" in a basic model (validating data before persisting into a database)

Jump to

Keyboard shortcuts

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