Skip to content

Commit e8da408

Browse files
jrschumacheraldas
authored andcommitted
Improve CustomValidator code
Add missing headers and fix Validator duplicating error messages
1 parent 9e53b0e commit e8da408

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

website/content/guide/request.md

+13-2
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,16 @@ a custom validator using `Echo#Validator` and leverage third-party [libraries](h
8484
Example below uses https://github.com/go-playground/validator framework for validation:
8585

8686
```go
87+
package main
88+
89+
import (
90+
"net/http"
91+
92+
"github.com/go-playground/validator"
93+
"github.com/labstack/echo/v4"
94+
"github.com/labstack/echo/v4/middleware"
95+
)
96+
8797
type (
8898
User struct {
8999
Name string `json:"name" validate:"required"`
@@ -97,7 +107,8 @@ type (
97107

98108
func (cv *CustomValidator) Validate(i interface{}) error {
99109
if err := cv.validator.Struct(i); err != nil {
100-
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
110+
// Optionally, you could return the error to give each route more control over the status code
111+
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
101112
}
102113
return nil
103114
}
@@ -111,7 +122,7 @@ func main() {
111122
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
112123
}
113124
if err = c.Validate(u); err != nil {
114-
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
125+
return err
115126
}
116127
return c.JSON(http.StatusOK, u)
117128
})

0 commit comments

Comments
 (0)