38 lines
942 B
Go
38 lines
942 B
Go
package api
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/go-playground/validator/v10"
|
|
)
|
|
|
|
type apiValidationError struct {
|
|
Field string `json:"field"`
|
|
Err string `json:"error"`
|
|
}
|
|
|
|
func getValidationErrors(ve *validator.ValidationErrors) []apiValidationError {
|
|
errors := make([]apiValidationError, len(*ve))
|
|
for i, fe := range *ve {
|
|
errors[i] = apiValidationError{
|
|
Field: fe.Field(),
|
|
Err: computeValidationMessage(&fe),
|
|
}
|
|
}
|
|
return errors
|
|
}
|
|
|
|
func computeValidationMessage(fe *validator.FieldError) string {
|
|
tag := (*fe).Tag()
|
|
switch tag {
|
|
case "required":
|
|
return fmt.Sprintf("%s is required.", (*fe).Field())
|
|
case "min":
|
|
return fmt.Sprintf("%s is not long enough. It should be at least %s characters.", (*fe).Field(), (*fe).Param())
|
|
case "max":
|
|
return fmt.Sprintf("%s is too long. It should be under %s characters.", (*fe).Field(), (*fe).Param())
|
|
default:
|
|
return fmt.Sprintf("Validation failed for '%s' property.", tag)
|
|
}
|
|
}
|