Skip to content

govalid is a lightweight and flexible validation library for Go that simplifies struct validation using tags.

Notifications You must be signed in to change notification settings

harrysan/govalid

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

21 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

GoValid

GoValid is a lightweight validation library for Golang designed to simplify data structure validation using tags in structs. It supports built-in rules like required, min, max, and email, and allows users to define custom validation rules.


🎯 Features

  • βœ… Tag-based validation for structs.
  • βœ… Built-in rules:
    • required: Ensures the field is not empty.
    • min: Minimum value for integers.
    • max: Maximum value for integers.
    • email: Validates email format.
  • βœ… Support for custom rules.
  • βœ… Easy-to-follow documentation and examples.

πŸš€ Installation

Install the library using go get:

go get github.com/harrysan/govalid


πŸ”§ Usage

1. Validate Structs with Built-In Rules

Use the validate tag to define rules for your struct fields.

package main

import (
	"fmt"
	"github.com/harrysan/govalid"
)

type User struct {
	Name  string validate:"required,min=3"
	Age   int    validate:"min=18,max=99"
	Email string validate:"required,email"
}

func main() {
	user := User{
		Name:  "Jo",
		Age:   17,
		Email: "invalid-email",
	}

	errs := govalid.ValidateStruct(user)
	if len(errs) > 0 {
		fmt.Println("Validation Errors:")
		for _, err := range errs {
			fmt.Println(err)
		}
	} else {
		fmt.Println("Validation Passed!")
	}
}

Output:

Validation Errors:
Field 'Name' failed validation 'min=3': value must be greater than or equal to 3
Field 'Age' failed validation 'min=18': value must be greater than or equal to 18
Field 'Email' failed validation 'email': invalid email format

2. Conditional Validation

Conditional Validation: validate_if

Use validate_if to apply rules conditionally based on another field's value.

Example:

type User struct {
	IsActive bool   `validate:"isTrue"`
	Reason   string `validate_if:"IsActive=true,required"`
}

3. Slice and Map Validation

Use validate to apply rules on slice and maps.

Example:

type DataSlice struct {
	Names []string `validate:"slice,required,min=3"`
	Age   []int    `validate:"slice,max=30"`
	Email []string `validate:"slice,email"`
}
type DataMap struct {
	Names []string          `validate:"slice,required,min=3"`
	Tags  map[string]string `validate:"map,keys=required;min=3,values=required;min=5"`
}

4. Struct Validation

Use validate to apply rules on struct.

Example:

type Address struct {
	City    string `validate:"required"`
	ZipCode string `validate:"required,min=5"`
}

type UserStruct struct {
	Name    string  `validate:"required"`
	Age     int     `validate:"min=18"`
	Address Address `validate:"struct"`
}

5. Custom Error Message

Use error_message on validate tag to apply custom error message.

Example:

type UserCustomError struct {
	Age   int    `validate:"min=18" error_message:"Age must be at least 18"`
	Email string `validate:"regex=email" error_message:"Invalid email format"`
}

6. Add Custom Validation Rules

You can register custom validation rules using the RegisterCustomRule function.

package main

import (
	"fmt"
	"github.com/harrysan/govalid"
)

func main() {
	// Register a custom rule
	err := govalid.RegisterCustomRule("isEven", func(field string, value interface{}) error {
		v, ok := value.(int)
		if !ok {
			return fmt.Errorf("%s must be an integer", field)
		}
		if v%2 != 0 {
			return fmt.Errorf("%s must be an even number", field)
		}
		return nil
	})

	if err != nil {
		fmt.Println("Failed to register custom rule:", err)
		return
	}

	type Data struct {
		Number int validate:"isEven"
	}

	data := Data{Number: 3}
	errs := govalid.ValidateStruct(data)

	if len(errs) > 0 {
		fmt.Println("Validation Errors:")
		for _, err := range errs {
			fmt.Println(err)
		}
	} else {
		fmt.Println("Validation Passed!")
	}
}

Output:

Validation Errors:
Field 'Number' failed validation 'isEven': Number must be an even number

πŸ“œ Built-In Rules

Rule Description Example Tag
required Ensures the field is not empty. validate:"required"
min The field must be greater than or equal to a minimum value. validate:"min=3"
max The field must be less than or equal to a maximum value. validate:"max=10"
bool The field must be true / false. validate:"isTrue"
validate:"isFalse"
email The field must be in a valid email format. validate:"email"
regex Regex validation, rules in rules/regex_rules.go
for customΒ rules.AddOrUpdateRegexRule (see validate_regex_test.go)
validate:"regex=username"

βš™οΈ API Reference

1. ValidateStruct

func ValidateStruct(s interface{}) []ValidationError

2. RegisterCustomRule

func RegisterCustomRule(name string, rule CustomRule) error

Registers a custom validation rule with a unique name and a function that implements the rule.

3. ValidationError

Struct representing a validation error:

type ValidationError struct {
	Field string      // Name of the field that failed validation
	Tag   string      // The validation rule that failed
	Value interface{} // The value of the field that failed validation
	Err   error       // Details about the error
}

πŸ“‚ Project Structure

.
└── govalid/
    β”œβ”€β”€ go.mod
    β”œβ”€β”€ validator/
    β”‚   β”œβ”€β”€ validator.go   # Core validation logic
    β”‚   └── custom.go      # Custom rule support
    β”œβ”€β”€ rules/
    β”‚   β”œβ”€β”€ rules.go       # Rules for validation
    β”‚   β”œβ”€β”€ rules_if.go    # Rules for validation_if
    β”‚   └── regex_rules.go  # Regex rules
    β”œβ”€β”€ test/
    β”‚   β”œβ”€β”€ validate_string_test.go     # Example usage
    β”‚   β”œβ”€β”€ validate_custom_test.go     # Example usage
    β”‚   β”œβ”€β”€ validate_struct_test.go     # Example usage
    β”‚   └── etc..
    └── README.md          # Documentation

πŸ› οΈ Roadmap

Planned features for future updates:

  • Support for nested struct validation.
  • Customizable error messages (including multi-language support).
  • Validation for additional data types (e.g., float, time).

🀝 Contributing

Contributions are welcome! Feel free to open a pull request or report issues in the issues section.


πŸ“„ License

This library is licensed under the MIT License.


Happy coding ! 😊

About

govalid is a lightweight and flexible validation library for Go that simplifies struct validation using tags.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages