Validation
The validation package wraps go-playground/validator and produces user-friendly field error messages.
Import
Section titled “Import”import "github.com/slice-soft/ss-keel-core/validation"Validate
Section titled “Validate”func Validate(s any) []FieldErrorValidates a struct using validate struct tags. Returns nil if the struct is valid.
type CreateUserDTO struct { Name string `json:"name" validate:"required"` Email string `json:"email" validate:"required,email"` Age int `json:"age" validate:"min=18"`}
dto := CreateUserDTO{Name: "", Email: "invalid", Age: 15}errors := validation.Validate(&dto)
// errors:// [// { "field": "name", "message": "this field is required" },// { "field": "email", "message": "must be a valid email" },// { "field": "age", "message": "minimum 18 characters" },// ]FieldError
Section titled “FieldError”type FieldError struct { Field string `json:"field"` Message string `json:"message"`}Supported Tags & Messages
Section titled “Supported Tags & Messages”| Tag | Message |
|---|---|
required | this field is required |
email | must be a valid email |
min=N | minimum N characters |
max=N | maximum N characters |
uuid | must be a valid UUID |
uuid4 | must be a valid UUID |
numeric | must be a numeric value |
url | must be a valid URL |
For any unrecognized tag, the raw validator message is used as a fallback.
Integration with ParseBody
Section titled “Integration with ParseBody”Ctx.ParseBody calls Validate internally. You don’t need to call it manually when using ParseBody:
func (c *UserController) create(ctx *core.Ctx) error { var dto CreateUserDTO if err := ctx.ParseBody(&dto); err != nil { // 400 Bad Request — malformed JSON // 422 Unprocessable Entity — validation errors return err } // dto is valid here}The 422 response body:
{ "errors": [ { "field": "email", "message": "must be a valid email" }, { "field": "name", "message": "this field is required" } ]}Standalone Usage
Section titled “Standalone Usage”You can call Validate independently of ParseBody:
type UpdateProfileDTO struct { Bio string `validate:"max=500"` URL string `validate:"omitempty,url"`}
dto := UpdateProfileDTO{Bio: strings.Repeat("x", 600), URL: "not-a-url"}if errs := validation.Validate(&dto); errs != nil { // handle errs}Validate Tags Reference
Section titled “Validate Tags Reference”For a full list of available validator tags, see the go-playground/validator documentation.