Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ErrorsToString ¶
func ErrorsToString(errs []*ErrorResponse) string
ErrorsToString converts a slice of ErrorResponse to a single string.
Types ¶
type ErrorResponse ¶
type ErrorResponse struct {
Field string `json:"field"`
Tag string `json:"tag"`
Param string `json:"param,omitempty"`
Value string `json:"value,omitempty"`
}
ErrorResponse represents a single validation error.
func ValidateStruct ¶
func ValidateStruct(payload interface{}) []*ErrorResponse
ValidateStruct validates a struct and returns a slice of ErrorResponse. If payload is nil or not a struct, it returns a single ErrorResponse with Tag "invalid" rather than panicking.
Example ¶
ValidateStruct checks `validate` struct tags and returns one ErrorResponse per failing field. Field names come from the `json` tag.
package main
import (
"fmt"
"github.com/rahmadafandi/fibr/validator"
)
func main() {
type SignupInput struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=8"`
}
errs := validator.ValidateStruct(SignupInput{Email: "not-an-email", Password: "short"})
for _, e := range errs {
fmt.Printf("%s failed %q\n", e.Field, e.Tag)
}
}
Output: email failed "email" password failed "min"
Example (Valid) ¶
A valid struct returns no errors.
package main
import (
"fmt"
"github.com/rahmadafandi/fibr/validator"
)
func main() {
type SignupInput struct {
Email string `json:"email" validate:"required,email"`
}
errs := validator.ValidateStruct(SignupInput{Email: "user@example.com"})
fmt.Println("errors:", len(errs))
}
Output: errors: 0
type FieldLevel ¶
type FieldLevel = govalidator.FieldLevel
FieldLevel is re-exported so callers can write custom rules without importing the underlying validator library directly.
Click to show internal directories.
Click to hide internal directories.