50 lines
1.6 KiB
Go
50 lines
1.6 KiB
Go
package validation
|
|
|
|
import (
|
|
"regexp"
|
|
"strings"
|
|
"unicode"
|
|
|
|
"github.com/go-playground/validator/v10"
|
|
)
|
|
|
|
// RegisterCustomValidators registers custom validation rules
|
|
func RegisterCustomValidators(validate *validator.Validate) {
|
|
validate.RegisterValidation("nospace", validateNoSpace)
|
|
validate.RegisterValidation("alphanumunderscore", validateAlphaNumUnderscore)
|
|
validate.RegisterValidation("alphaspace", validateAlphaSpace) // Add this
|
|
validate.RegisterValidation("alphanum", validateAlphaNum) // Add this
|
|
|
|
RegisterPortValidators(validate) // Ensure port validators are registered
|
|
}
|
|
|
|
// validateNoSpace checks that the field contains no spaces
|
|
func validateNoSpace(fl validator.FieldLevel) bool {
|
|
value := fl.Field().String()
|
|
return !strings.Contains(value, " ")
|
|
}
|
|
|
|
// validateAlphaNumUnderscore allows alphanumeric characters and underscores only
|
|
func validateAlphaNumUnderscore(fl validator.FieldLevel) bool {
|
|
value := fl.Field().String()
|
|
matched, _ := regexp.MatchString("^[a-zA-Z0-9_]+$", value)
|
|
return matched
|
|
}
|
|
|
|
// validateAlphaSpace allows alphabetic characters and spaces only (for names)
|
|
func validateAlphaSpace(fl validator.FieldLevel) bool {
|
|
value := fl.Field().String()
|
|
for _, char := range value {
|
|
if !unicode.IsLetter(char) && char != ' ' {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// validateAlphaNum allows alphanumeric characters only
|
|
func validateAlphaNum(fl validator.FieldLevel) bool {
|
|
value := fl.Field().String()
|
|
matched, _ := regexp.MatchString("^[a-zA-Z0-9]+$", value)
|
|
return matched
|
|
} |