Zius is a Golang struct validator library.
To install Zius, you can use go get
:
go get github.com/vinibgoulart/zius
Here's a simple example of how to use Zius:
// Import the package
import "github.com/vinibgoulart/zius"
// Define your struct
type User struct {
Name string `zius:"required"`
Email string `zius:"required,email"`
}
// Validate your struct
func ValidateUser(user User) []Error, error {
return zius.Validate(user)
}
The Validate
function returns a slice of Error
and an error.
errors, err := ValidateUser(user)
The Error
struct has the following fields: Struct
, Field
, and Error
.
type Error struct {
Struct string
Field string
Error error
}
The error field contains the first error message.
Check the __examples__/with_multiple_errors/main.go
file for a complete example.
Zius comes with a number of built-in validators:
required
: Ensures the field is not emptyemail
: Validates that the field is a valid email addressnumber
: Validates that the field is a valid numberint
: Validates that the field is a valid integerphone
: Validates that the field is a valid phone numberregex
: Validates the field against a custom regular expressionequals
: Validates the field against a custom valuearray
: Validates that the field is an arraystruct
: Validates that the field is a struct
You can define a custom message for each validator like that:
type User struct {
Name string `zius:"required:Name is required"`
Email string `zius:"required:Email is required,email:Email must be a valid email"`
}
You can define a custom regular expression for the regex
validator sending the regex as a parameter:
type User struct {
Name string `zius:"regex={^([a-zA-Z]+)$}"`
}
In the example above, the Name
field will only be valid if it contains only letters.
You can define a custom value for the equals
validator sending the value as a parameter:
type User struct {
Name string `zius:"equals={John, Vinicius}"`
}
In the example above, the Name
field will only be valid if it is equal to John
or Vinicius
.
You can find more examples of how to use Zius in the __examples__
directory.
Contributions are welcome! Please feel free to submit a Pull Request.