From 7606c618d3e4950e9be66c3cbaff8aa457aa78f3 Mon Sep 17 00:00:00 2001 From: Mazyar Yousefiniyae shad Date: Tue, 25 Mar 2025 10:55:56 +0330 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=9A=20Doc:=20Add=20more=20validation?= =?UTF-8?q?=20examples=20(#3369)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * add examples on valudator guid * ref: return prev validation comment --- docs/guide/validation.md | 71 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 69 insertions(+), 2 deletions(-) diff --git a/docs/guide/validation.md b/docs/guide/validation.md index 7226347f..fd007a62 100644 --- a/docs/guide/validation.md +++ b/docs/guide/validation.md @@ -8,8 +8,7 @@ sidebar_position: 5 Fiber provides the [Bind](../api/bind.md#validation) function to validate and bind [request data](../api/bind.md#binders) to a struct. -```go title="Example" - +```go title="Basic Example" import "github.com/go-playground/validator/v10" type structValidator struct { @@ -42,3 +41,71 @@ app.Post("/", func(c fiber.Ctx) error { return c.JSON(user) }) ``` + +```go title="Advanced Validation Example" +type User struct { + Name string `json:"name" validate:"required,min=3,max=32"` + Email string `json:"email" validate:"required,email"` + Age int `json:"age" validate:"gte=0,lte=100"` + Password string `json:"password" validate:"required,min=8"` + Website string `json:"website" validate:"url"` +} + +// Custom validation error messages +type UserWithCustomMessages struct { + Name string `json:"name" validate:"required,min=3,max=32" message:"Name is required and must be between 3 and 32 characters"` + Email string `json:"email" validate:"required,email" message:"Valid email is required"` + Age int `json:"age" validate:"gte=0,lte=100" message:"Age must be between 0 and 100"` +} + +app.Post("/user", func(c fiber.Ctx) error { + user := new(User) + + if err := c.Bind().Body(user); err != nil { + // Handle validation errors + if validationErrors, ok := err.(validator.ValidationErrors); ok { + for _, e := range validationErrors { + // e.Field() - field name + // e.Tag() - validation tag + // e.Value() - invalid value + // e.Param() - validation parameter + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ + "field": e.Field(), + "error": e.Error(), + }) + } + } + return err + } + + return c.JSON(user) +}) +``` + +```go title="Custom Validator Example" +// Custom validator for password strength +type PasswordValidator struct { + validate *validator.Validate +} + +func (v *PasswordValidator) Validate(out any) error { + if err := v.validate.Struct(out); err != nil { + return err + } + + // Custom password validation logic + if user, ok := out.(*User); ok { + if len(user.Password) < 8 { + return errors.New("password must be at least 8 characters") + } + // Add more password validation rules here + } + + return nil +} + +// Usage +app := fiber.New(fiber.Config{ + StructValidator: &PasswordValidator{validate: validator.New()}, +}) +```