Validator & Echo: Fields are not validated

Hi there, I’m new to echo & validators. The problem is, they never trigger, whatever I curl, e.g.:

curl -X POST localhost:3000/user

Should not return an empty user b/c min=5 is not matched obviously.

Here is my demo code:

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/go-playground/validator/v10"
	"github.com/labstack/echo/v4"
)

type User struct {
	Email string `json:"email" form:"email" validate:"required,email"`
	Name  string `json:"name"               validate:"required,min=5"`
}

func (u User) String() string {
	return fmt.Sprintf("Name: %s | Email: %s", u.Name, u.Email)
}

type ResponseError struct {
	Message string `json:"message"`
}

type Validator struct {
	validator *validator.Validate
}

func (v *Validator) Validate(i interface{}) error {
	err := v.validator.Struct(i)
	if err != nil {
		return nil
	}
	return nil
}

func main() {

	e := echo.New()
	e.Validator = &Validator{validator: validator.New()}

	e.POST("/user", func(c echo.Context) error {
		var user User

		if err := c.Bind(&user); err != nil {
			return c.JSON(http.StatusBadRequest, ResponseError{Message: err.Error()})
		}
		log.Println(user)

		if err := c.Validate(&user); err != nil {
			return c.JSON(http.StatusBadRequest, ResponseError{Message: err.Error()})
		}
		return c.JSON(http.StatusOK, user)

	})

	e.Logger.Fatal(e.Start(":3000"))

}

Am I misunderstanding what validator.Struct() is doing?

Thanks!

when err , you still return nil, thats the root cause
you can just
return v.validator.Struct(i)
like this

func (v *Validator) Validate(i interface{}) error {
	return v.validator.Struct(i)
}
1 Like