validate

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2026 License: GPL-3.0 Imports: 10 Imported by: 3

README

⚡  go-validate

Powerful struct field validation via tags plus extra validation utilities.


Release Go Version License


CI / CD    Build Last Commit      Quality    Go Report Coverage
Security    Scorecard Security      Community    Contributors Bitcoin


Project Navigation
🚀 Installation 🧪 Examples & Tests 📚 Documentation
🤝 Contributing 🛠️ Code Standards ⚡ Benchmarks
🤖 AI Usage ⚖️ License 👥 Maintainers

Installation

go-validate requires a supported release of Go.

go get github.com/mrz1836/go-validate

Documentation

View the generated documentation

Heads up! go-validate is intentionally light on dependencies. The only external package it uses is the excellent testify suite—and that's just for our tests. You can drop this library into your projects without dragging along extra baggage.

Development Setup (Getting Started)

Install MAGE-X build tool for development:

# Install MAGE-X for development and building
go install github.com/mrz1836/mage-x/cmd/magex@latest
magex update:install
Library Deployment

This project uses goreleaser for streamlined binary and library deployment to GitHub. To get started, install it via:

brew install goreleaser

The release process is defined in the .goreleaser.yml configuration file.

Then create and push a new Git tag using:

magex version:bump bump=patch push=true branch=master

This process ensures consistent, repeatable releases with properly versioned artifacts and citation metadata.

Build Commands

View all build commands

magex help
GitHub Workflows

All workflows are driven by modular configuration in .github/env/ — no YAML editing required.

View all workflows and the control center →

Updating Dependencies

To update all dependencies (Go modules, linters, and related tools), run:

magex deps:update

This command ensures all dependencies are brought up to date in a single step, including Go modules and any managed tools. It is the recommended way to keep your development environment and CI in sync with the latest versions.


Examples & Tests

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

Run all tests (fast):

magex test

Run all tests with race detector (slower):

magex test:race
Examples demonstrating various validation scenarios.
Basic Struct Validation
package main

import (
    "fmt"
    "log"

    "github.com/mrz1836/go-validate"
)

type User struct {
    Name     string `validation:"min_length=2 max_length=50"`
    Email    string `validation:"format=email"`
    Age      uint   `validation:"min=18 max=120"`
    Username string `validation:"min_length=3 max_length=20"`
}

func main() {
    // Initialize validations (required)
    validate.InitValidations()

    user := User{
        Name:     "John Doe",
        Email:    "john@example.com",
        Age:      25,
        Username: "johndoe",
    }

    // Validate the struct
    isValid, errors := validate.IsValid(user)
    if !isValid {
        for _, err := range errors {
            fmt.Printf("Validation error: %s\n", err.Error())
        }
    } else {
        fmt.Println("User is valid!")
    }
}
Password Confirmation Example
package main

import (
    "fmt"

    "github.com/mrz1836/go-validate"
)

type RegistrationForm struct {
    Email                string `validation:"format=email"`
    Password             string `validation:"min_length=8"`
    PasswordConfirmation string `validation:"compare=Password"`
    TermsAccepted        bool   // No validation needed
}

func main() {
    validate.InitValidations()

    form := RegistrationForm{
        Email:                "user@domain.com",
        Password:             "SecurePass123",
        PasswordConfirmation: "SecurePass123", // Must match Password field
        TermsAccepted:        true,
    }

    isValid, errors := validate.IsValid(form)
    if !isValid {
        fmt.Println("Registration form has errors:")
        for _, err := range errors {
            fmt.Printf("- %s\n", err.Error())
        }
    } else {
        fmt.Println("Registration form is valid!")
    }
}
Custom Regex Validation
package main

import (
    "fmt"

    "github.com/mrz1836/go-validate"
)

type Product struct {
    SKU         string  `validation:"format=regexp:^[A-Z]{2,3}[0-9]{4,6}$"`
    Name        string  `validation:"min_length=1 max_length=100"`
    Price       float64 `validation:"min=0.01"`
    Description string  `validation:"max_length=500"`
}

func main() {
    validate.InitValidations()

    product := Product{
        SKU:         "AB12345",  // Must match pattern: 2-3 uppercase letters + 4-6 digits
        Name:        "Wireless Headphones",
        Price:       99.99,
        Description: "High-quality wireless headphones with noise cancellation",
    }

    isValid, errors := validate.IsValid(product)
    if !isValid {
        fmt.Println("Product validation failed:")
        for _, err := range errors {
            fmt.Printf("- %s\n", err.Error())
        }
    } else {
        fmt.Println("Product is valid!")
    }
}
Using Extra Validation Functions
package main

import (
    "fmt"

    "github.com/mrz1836/go-validate"
)

type Contact struct {
    Name        string
    Email       string
    Phone       string
    Website     string
    CountryCode string
}

func (c *Contact) Validate() (bool, []validate.ValidationError) {
    var errors []validate.ValidationError

    // Email validation with MX record check
    if valid, err := validate.IsValidEmail(c.Email, true); !valid {
        errors = append(errors, validate.ValidationError{
            Key:     "Email",
            Message: err.Error(),
        })
    }

    // Phone number validation (US/Canada/Mexico)
    if valid, err := validate.IsValidPhoneNumber(c.Phone, c.CountryCode); !valid {
        errors = append(errors, validate.ValidationError{
            Key:     "Phone",
            Message: err.Error(),
        })
    }

    // Website host validation
    if c.Website != "" && !validate.IsValidHost(c.Website) {
        errors = append(errors, validate.ValidationError{
            Key:     "Website",
            Message: "is not a valid host or IP address",
        })
    }

    return len(errors) == 0, errors
}

func main() {
    contact := Contact{
        Name:        "Jane Smith",
        Email:       "jane@protonmail.com",
        Phone:       "555-123-4567",
        Website:     "janesmith.dev",
        CountryCode: "1", // USA/Canada
    }

    isValid, errors := contact.Validate()
    if !isValid {
        fmt.Println("Contact validation failed:")
        for _, err := range errors {
            fmt.Printf("- %s\n", err.Error())
        }
    } else {
        fmt.Println("Contact is valid!")
    }
}
Custom Validation Implementation
package main

import (
    "fmt"
    "reflect"
    "strings"

    "github.com/mrz1836/go-validate"
)

// Custom validation for allowed colors
type colorValidation struct {
    validate.Validation
    allowedColors []string
}

func (c *colorValidation) Validate(value interface{}, _ reflect.Value) *validate.ValidationError {
    strValue, ok := value.(string)
    if !ok {
        return &validate.ValidationError{
            Key:     c.FieldName(),
            Message: "must be a string",
        }
    }

    // Check if color is in allowed list
    for _, color := range c.allowedColors {
        if strings.EqualFold(strValue, color) {
            return nil // Valid
        }
    }

    return &validate.ValidationError{
        Key:     c.FieldName(),
        Message: fmt.Sprintf("must be one of: %s", strings.Join(c.allowedColors, ", ")),
    }
}

// Builder function for the custom validation
func colorValidationBuilder(colors string, _ reflect.Kind) (validate.Interface, error) {
    allowedColors := strings.Split(colors, ",")
    for i, color := range allowedColors {
        allowedColors[i] = strings.TrimSpace(color)
    }

    return &colorValidation{
        allowedColors: allowedColors,
    }, nil
}

type Car struct {
    Make  string `validation:"min_length=1"`
    Model string `validation:"min_length=1"`
    Year  int    `validation:"min=1900 max=2024"`
    Color string `validation:"color=red,blue,green,black,white,silver"`
}

func main() {
    // Register our custom validation
    validate.AddValidation("color", colorValidationBuilder)
    validate.InitValidations()

    car := Car{
        Make:  "Toyota",
        Model: "Camry",
        Year:  2023,
        Color: "blue", // Must be one of the allowed colors
    }

    isValid, errors := validate.IsValid(car)
    if !isValid {
        fmt.Println("Car validation failed:")
        for _, err := range errors {
            fmt.Printf("- %s\n", err.Error())
        }
    } else {
        fmt.Println("Car is valid!")
    }
}
Enum Validation Example
package main

import (
    "fmt"

    "github.com/mrz1836/go-validate"
)

type OrderStatus string

const (
    StatusPending   OrderStatus = "pending"
    StatusShipped   OrderStatus = "shipped"
    StatusDelivered OrderStatus = "delivered"
    StatusCancelled OrderStatus = "cancelled"
)

type Order struct {
    ID       string
    Status   string
    Priority string
}

func (o *Order) Validate() (bool, []validate.ValidationError) {
    var errors []validate.ValidationError

    // Validate order status using enum validation
    allowedStatuses := []string{"pending", "shipped", "delivered", "cancelled"}
    if valid, err := validate.IsValidEnum(o.Status, &allowedStatuses, false); !valid {
        errors = append(errors, validate.ValidationError{
            Key:     "Status",
            Message: err.Error(),
        })
    }

    // Validate priority with empty allowed
    allowedPriorities := []string{"low", "medium", "high", "urgent"}
    if valid, err := validate.IsValidEnum(o.Priority, &allowedPriorities, true); !valid {
        errors = append(errors, validate.ValidationError{
            Key:     "Priority",
            Message: err.Error(),
        })
    }

    return len(errors) == 0, errors
}

func main() {
    order := Order{
        ID:       "ORD-12345",
        Status:   "shipped",    // Valid status
        Priority: "",           // Empty allowed for priority
    }

    isValid, errors := order.Validate()
    if !isValid {
        fmt.Println("Order validation failed:")
        for _, err := range errors {
            fmt.Printf("- %s\n", err.Error())
        }
    } else {
        fmt.Println("Order is valid!")
    }
}
Complete Model Validation
package main

import (
    "fmt"

    "github.com/mrz1836/go-validate"
)

// Customer model with comprehensive validation
type Customer struct {
    // Basic info with struct tags
    FirstName string `validation:"min_length=2 max_length=50"`
    LastName  string `validation:"min_length=2 max_length=50"`
    Email     string `validation:"format=email"`
    Age       uint8  `validation:"min=18 max=120"`

    // Address info
    Address string `validation:"min_length=10 max_length=200"`
    City    string `validation:"min_length=2 max_length=50"`
    State   string `validation:"min_length=2 max_length=2"` // US state codes
    ZipCode string `validation:"format=regexp:^[0-9]{5}(-[0-9]{4})?$"`

    // Contact info (validated separately)
    Phone               string `json:"phone"`
    SocialSecurityNumber string `json:"-"`

    // Account info
    AccountType    string  `validation:"min_length=1"`
    InitialBalance float64 `validation:"min=0"`
}

// Custom validation method that combines struct tags with utility functions
func (c *Customer) Validate() (bool, []validate.ValidationError) {
    // First run struct tag validations
    _, errors := validate.IsValid(*c)

    // Add phone number validation
    if valid, err := validate.IsValidPhoneNumber(c.Phone, "1"); !valid && c.Phone != "" {
        errors = append(errors, validate.ValidationError{
            Key:     "Phone",
            Message: err.Error(),
        })
    }

    // Add SSN validation
    if valid, err := validate.IsValidSocial(c.SocialSecurityNumber); !valid {
        errors = append(errors, validate.ValidationError{
            Key:     "SocialSecurityNumber",
            Message: err.Error(),
        })
    }

    // Add account type enum validation
    allowedTypes := []string{"checking", "savings", "business", "premium"}
    if valid, err := validate.IsValidEnum(c.AccountType, &allowedTypes, false); !valid {
        errors = append(errors, validate.ValidationError{
            Key:     "AccountType",
            Message: err.Error(),
        })
    }

    return len(errors) == 0, errors
}

func main() {
    validate.InitValidations()

    customer := Customer{
        FirstName:            "Alice",
        LastName:             "Johnson",
        Email:                "alice.johnson@email.com",
        Age:                  28,
        Address:              "123 Main Street, Apt 4B",
        City:                 "New York",
        State:                "NY",
        ZipCode:              "10001",
        Phone:                "555-123-4567",
        SocialSecurityNumber: "123-45-6789", // This will fail validation (blacklisted)
        AccountType:          "checking",
        InitialBalance:       1000.00,
    }

    isValid, errors := customer.Validate()
    if !isValid {
        fmt.Printf("Customer validation failed with %d errors:\n", len(errors))
        for i, err := range errors {
            fmt.Printf("%d. %s\n", i+1, err.Error())
        }
    } else {
        fmt.Println("Customer validation passed! Ready to save to database.")
    }
}

Benchmarks

Run the Go benchmarks:

magex bench

Code Standards

Read more about this Go project's code standards.


🤖 AI Usage & Assistant Guidelines

Read the AI Usage & Assistant Guidelines for details on how AI is used in this project and how to interact with AI assistants.


Maintainers

MrZ
MrZ

Contributing

View the contributing guidelines and please 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! 🚀

Stars


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 (
	// Enum validation errors
	ErrEnumValueNotAllowed = errors.New("value is not allowed")

	// Email validation errors
	ErrEmailLengthInvalid       = errors.New("email length is invalid")
	ErrEmailFormatInvalid       = errors.New("email is not a valid address format")
	ErrEmailMissingAtSign       = errors.New("email is missing the @ sign")
	ErrEmailMultipleAtSigns     = errors.New("email contains more than one @ sign")
	ErrEmailDomainNotAccepted   = errors.New("email domain is not accepted")
	ErrEmailDomainInvalidHost   = errors.New("email domain is not a valid host")
	ErrEmailDomainCannotReceive = errors.New("email domain invalid/cannot receive mail")

	// Social Security validation errors
	ErrSocialEmpty          = errors.New("social is empty")
	ErrSocialLengthInvalid  = errors.New("social is not nine digits in length")
	ErrSocialRegexMismatch  = errors.New("social does not match the regex pattern")
	ErrSocialSectionInvalid = errors.New("social section was found invalid (cannot be 000 or 666)")
	ErrSocialBlacklisted    = errors.New("social was found to be blacklisted")

	// Phone number validation errors
	ErrCountryCodeLengthInvalid = errors.New("country code length is invalid")
	ErrCountryCodeNotAccepted   = errors.New("country code is not accepted")
	ErrPhoneLengthInvalid       = errors.New("phone number length is invalid")
	ErrPhoneMustBeTenDigits     = errors.New("phone number must be ten digits")
	ErrPhoneNPAInvalidStart     = errors.New("phone number NPA cannot start with specified digit")
	ErrPhoneNXXInvalidDigits    = errors.New("phone number NXX cannot be specified digits")
	ErrPhoneMustBeEightOrTen    = errors.New("phone number must be either eight or ten digits")
)

Static error definitions to satisfy err113 linter

View Source
var DefaultMap = Map{} //nolint:gochecknoglobals // Default package-level validation map

DefaultMap is the default validation map used to tell if a struct is valid. Global by design to provide a shared default instance across the package.

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 InitValidations added in v1.0.0

func InitValidations()

InitValidations registers all built-in validations. This function is safe to call multiple times and will only execute once. It must be called before using any validation features.

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 is not allowed: 1
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, 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>

func RegisterNumericValidations added in v1.0.0

func RegisterNumericValidations()

RegisterNumericValidations registers all numeric validations

func RegisterStringValidations added in v1.0.0

func RegisterStringValidations()

RegisterStringValidations registers all string validations

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"` //nolint:gosec // test struct demonstrating password comparison validation
	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