Last active
February 15, 2025 04:23
-
-
Save defrindr/3b5cddf120e30a2826090814209c265a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package utils | |
import ( | |
"regexp" | |
"strings" | |
"github.com/go-playground/validator/v10" | |
) | |
// Convert field names from CamelCase to snake_case | |
func toSnakeCase(input string) string { | |
// Use a regular expression to insert underscores before uppercase letters | |
re := regexp.MustCompile("([a-z0-9])([A-Z])") | |
snake := re.ReplaceAllString(input, "${1}_${2}") | |
// Convert the entire string to lowercase | |
return strings.ToLower(snake) | |
} | |
// Map validation tags to custom error messages | |
func getErrorMessage(tag string) string { | |
switch tag { | |
case "required": | |
return "Field must be filled" | |
case "unique": | |
return "This value already exists" | |
case "gt": // greater than | |
return "Value must be greater than the minimum allowed" | |
case "gte": // greater than or equal | |
return "Value must be greater than or equal to the minimum allowed" | |
case "lt": // less than | |
return "Value must be less than the maximum allowed" | |
case "lte": // less than or equal | |
return "Value must be less than or equal to the maximum allowed" | |
case "email": | |
return "Invalid email format" | |
case "min": | |
return "Value is too short" | |
case "max": | |
return "Value is too long" | |
default: | |
return "Invalid input" | |
} | |
} | |
// ParseValidationErrors converts validation errors into JSON format | |
func LaravelLikeValidatorErrors(err error) map[string][]string { | |
validationErrors := make(map[string][]string) | |
// Handle go-playground/validator errors | |
if errs, ok := err.(validator.ValidationErrors); ok { | |
for _, e := range errs { | |
fieldName := toSnakeCase(e.Field()) // Convert to snake_case | |
validationErrors[fieldName] = append(validationErrors[fieldName], getErrorMessage(e.Tag())) | |
} | |
} else { | |
// Handle generic errors (manual validation) | |
re := regexp.MustCompile(`Key: '([^']+)'.+?failed on the '([^']+)' tag`) | |
matches := re.FindStringSubmatch(err.Error()) | |
if len(matches) == 3 { | |
fieldName := toSnakeCase(matches[1]) // Convert to snake_case | |
validationErrors[fieldName] = append(validationErrors[fieldName], getErrorMessage(matches[2])) | |
} else { | |
validationErrors["error"] = []string{err.Error()} | |
} | |
} | |
return validationErrors | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment