mirror of
https://github.com/hazemKrimi/crimson-vault.git
synced 2026-05-01 18:20:27 +00:00
chore: custom validation error messages
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user