Files
dyn/internal/handlers/validation.go

46 lines
1.2 KiB
Go

package handlers
import (
"regexp"
"strings"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
)
func init() {
// Register custom validators
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("alphanumdash", alphanumdashValidator)
}
}
// alphanumdashValidator validates that a string contains only alphanumeric characters and hyphens
var alphanumdashValidator validator.Func = func(fl validator.FieldLevel) bool {
value := fl.Field().String()
// Allow alphanumeric and hyphens only
match := regexp.MustCompile(`^[a-zA-Z0-9-]+$`).MatchString(value)
return match
}
// IsValidSubdomainFormat checks if a subdomain string is valid (exported for use in validation)
func IsValidSubdomainFormat(subdomain string) bool {
// Must be at least 3 characters
if len(subdomain) < 3 {
return false
}
// Must not exceed 63 characters
if len(subdomain) > 63 {
return false
}
// Must not start or end with hyphen
if strings.HasPrefix(subdomain, "-") || strings.HasSuffix(subdomain, "-") {
return false
}
// Must contain only alphanumeric and hyphens
return regexp.MustCompile(`^[a-zA-Z0-9-]+$`).MatchString(subdomain)
}