feat: improve support for instance ID tag

This commit is contained in:
Gareth
2024-05-05 08:55:21 -07:00
parent f314c7cced
commit be0cdd59be
9 changed files with 162 additions and 88 deletions

View File

@@ -0,0 +1,33 @@
package validationutil
import (
"errors"
"fmt"
"regexp"
)
var (
IDMaxLen = 50 // maximum length of an ID
sanitizeIDRegex = regexp.MustCompile(`[^a-zA-Z0-9_\-\.]+`) // matches invalid characters in an ID
idRegex = regexp.MustCompile(`[a-zA-Z0-9_\-\.]*`) // matches a valid ID (including empty string)
)
func SanitizeID(id string) string {
return sanitizeIDRegex.ReplaceAllString(id, "_")
}
// ValidateID checks if an ID is valid.
// It returns an error if the ID contains invalid characters, is empty, or is too long.
// The maxLen parameter is the maximum length of the ID. If maxLen is 0, the ID length is not checked.
func ValidateID(id string, maxLen int) error {
if !idRegex.MatchString(id) {
return errors.New("contains invalid characters")
}
if len(id) == 0 {
return errors.New("empty")
}
if maxLen > 0 && len(id) > maxLen {
return fmt.Errorf("too long (> %d chars)", maxLen)
}
return nil
}