mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-20 13:31:56 +00:00
initial commit
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
package validation
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
var customMessages = map[string]string{
|
||||
"required": "Field %s is required",
|
||||
"required_strict": "Field %s is required and cannot be null or empty",
|
||||
"omitempty_strict": "Field %s cannot be null or empty when provided",
|
||||
|
||||
"email": "Invalid email address for field %s",
|
||||
"min": "Field %s must have a minimum length of %s characters",
|
||||
"max": "Field %s must have a maximum length of %s characters",
|
||||
"len": "Field %s must be exactly %s characters long",
|
||||
"number": "Field %s must be a number",
|
||||
"positive": "Field %s must be a positive number",
|
||||
"alphanum": "Field %s must contain only alphanumeric characters",
|
||||
"oneof": "Invalid value for field %s",
|
||||
"password": "Field %s must be at least 8 characters, contain uppercase, lowercase, number, and special character",
|
||||
}
|
||||
|
||||
func CustomErrorMessages(err error) map[string]string {
|
||||
var validationErrors validator.ValidationErrors
|
||||
if errors.As(err, &validationErrors) {
|
||||
return generateErrorMessages(validationErrors)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateErrorMessages(validationErrors validator.ValidationErrors) map[string]string {
|
||||
errorsMap := make(map[string]string)
|
||||
for _, err := range validationErrors {
|
||||
fieldName := err.StructNamespace()
|
||||
tag := err.Tag()
|
||||
|
||||
customMessage := customMessages[tag]
|
||||
if customMessage != "" {
|
||||
errorsMap[fieldName] = formatErrorMessage(customMessage, err, tag)
|
||||
} else {
|
||||
errorsMap[fieldName] = defaultErrorMessage(err)
|
||||
}
|
||||
}
|
||||
return errorsMap
|
||||
}
|
||||
|
||||
func formatErrorMessage(customMessage string, err validator.FieldError, tag string) string {
|
||||
if tag == "min" || tag == "max" || tag == "len" {
|
||||
return fmt.Sprintf(customMessage, err.Field(), err.Param())
|
||||
}
|
||||
return fmt.Sprintf(customMessage, err.Field())
|
||||
}
|
||||
|
||||
func defaultErrorMessage(err validator.FieldError) string {
|
||||
return fmt.Sprintf("Field validation for '%s' failed on the '%s' tag", err.Field(), err.Tag())
|
||||
}
|
||||
|
||||
func Validator() *validator.Validate {
|
||||
validate := validator.New()
|
||||
|
||||
if err := validate.RegisterValidation("password", Password); err != nil {
|
||||
return nil
|
||||
}
|
||||
if err := validate.RegisterValidation("required_strict", RequiredStrict); err != nil {
|
||||
return nil
|
||||
}
|
||||
if err := validate.RegisterValidation("omitempty_strict", OmitemptyStrict); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return validate
|
||||
}
|
||||
Reference in New Issue
Block a user