govalidate
is a lightweight Go package for validating values using regular expressions. It allows you to define custom
validation patterns, apply them to individual values, and recursively validate struct fields based on tags. The package
is designed to be thread-safe and efficient, making it suitable for a variety of use cases where data validation is
required.
- Pattern Management: Add, remove, and validate patterns using regular expressions.
- Struct Validation: Validate struct fields based on custom tags.
- Thread-Safe: Safe for concurrent use across multiple goroutines.
- Custom Error Handling: Provides clear and informative error messages for validation failures.
To use goapitest
in your Go project, you need to install it using Go modules. You can add it to your project with the
following command:
go get -u github.com/tvative/govalidate
First, initialize a Config
instance, which will hold your patterns:
package main
import (
"github.com/tvative/govalidate"
)
func main() {
validator := govalidate.Initialize()
// Add patterns and use validator here
}
Add a new regular expression pattern to your validator:
err := validator.AddPattern("email", `^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$`)
if err != nil {
fmt.Println("Error adding pattern:", err)
}
Validate a value against a stored pattern:
isValid := validator.Validate("email", "[email protected]")
fmt.Println("Is valid email:", isValid) // Output: true
Remove a pattern from the validator:
validator.RemovePattern("email")
You can validate struct fields by using custom tags:
type User struct {
Name string `json:"name" rules:"required"`
Email string `json:"email" rules:"required" pattern:"email"`
}
func main() {
user := User{Name: "John Doe", Email: "invalid-email"}
valid, err := validator.ValidateStruct(user)
if !valid {
fmt.Println("Validation error:", err)
}
}
pattern:"<pattern_name>"
: Validates the field value against the specified pattern.rules:"required"
: Ensures that the field is not empty.rules:"empty"
: Allows the field to be empty.
For a minimal example, see the tests/main.go file. That file contains a simple example of how to use the package.
This project is licensed under the MIT License; see the LICENSE file for details.