added validation when adding a book
This commit is contained in:
35
internal/api/validator.go
Normal file
35
internal/api/validator.go
Normal file
@@ -0,0 +1,35 @@
|
||||
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 "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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user