chore: custom validation error messages

This commit is contained in:
2025-06-05 02:53:04 +01:00
parent b70bdba0dc
commit a67726919d
4 changed files with 45 additions and 12 deletions
+34 -3
View File
@@ -1,6 +1,7 @@
package api
import (
"fmt"
"net/http"
"regexp"
@@ -12,10 +13,40 @@ type CustomValidator struct {
validator *validator.Validate
}
func (validator *CustomValidator) Validate(i any) error {
if err := validator.validator.Struct(i); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
func (v *CustomValidator) Validate(i any) error {
if err := v.validator.Struct(i); err != nil {
if validationErrors, ok := err.(validator.ValidationErrors); ok {
errors := make(map[string]string)
for _, ve := range validationErrors {
field := ve.Field()
tag := ve.Tag()
var msg string
switch tag {
case "required":
msg = fmt.Sprintf("%s is required!", field)
case "email":
msg = fmt.Sprintf("%s must be a valid email!", field)
case "alpha":
msg = fmt.Sprintf("%s must only contain alphabetic characters!", field)
case "e164":
msg = fmt.Sprintf("%s must be a valid phone number in e164 format!", field)
case "password":
msg = fmt.Sprintf("%s must have at lease one uppercase, one lowercase, one number and one special character!", field)
case "eqcsfield":
msg = fmt.Sprintf("%s must be the same as %s!", field, ve.Param())
default:
msg = fmt.Sprintf("%s is not valid!", field)
}
errors[field] = msg
}
return echo.NewHTTPError(http.StatusBadRequest, errors)
}
}
return nil
}