Struct field validation via tags. Supports nonzero and email rules.
Go applications frequently need to validate user input, config values, or API
payloads before processing them. The standard library has no built-in struct
validation — every project ends up writing boilerplate if checks. This
package provides a small, tag-based validator with zero external dependencies.
import "github.com/azghr/forge/validator"
type User struct {
Name string `validate:"nonzero"`
Email string `validate:"email"`
}
u := User{Name: "Alice", Email: "x@x"}
if err := validator.ValidateStruct(u); err != nil {
log.Fatal(err)
}ValidateStruct(v interface{}, opts ...Option) error— validate all exported fields of a struct by theirvalidatetags. Returns aValidationErroron failure, ornilif all fields pass.
WithTagName(name string) Option— set the struct tag key (default"validate").
| Tag | Applies to | Description |
|---|---|---|
nonzero |
string, int, bool, ptr, slice, map, etc. | Value must not be the zero value for its type |
email |
string | Value must match a basic email pattern |
ValidationError—[]FieldErrorthat implementserror. EachFieldErrorcontainsField(name),Tag(failed rule), andValue.
Uses reflection once per call. Benchmark on Apple M1 Max:
- Valid struct: ~500 ns/op
- Invalid struct: ~600 ns/op