78 lines
1.5 KiB
Go
78 lines
1.5 KiB
Go
package util
|
|
|
|
import (
|
|
"strings"
|
|
"unicode"
|
|
)
|
|
|
|
// Allowed special characters
|
|
const specialChars = "!@#$%^*-_=+~()[]{}"
|
|
|
|
var allowedSpecialChars map[rune]bool
|
|
|
|
func init() {
|
|
allowedSpecialChars = make(map[rune]bool)
|
|
for _, r := range []rune(specialChars) {
|
|
allowedSpecialChars[r] = true
|
|
}
|
|
}
|
|
|
|
func ValidateTypeName(input string) (string, bool) {
|
|
// Trim leading and trailing spaces
|
|
trimmed := strings.TrimSpace(input)
|
|
|
|
// If the string is empty after trimming, return false
|
|
if len(trimmed) == 0 {
|
|
return "", false
|
|
}
|
|
|
|
runes := []rune(trimmed)
|
|
|
|
if len(runes) > 30 {
|
|
return "", false
|
|
}
|
|
|
|
// Dash cannot be at the beginning or end
|
|
if allowedSpecialChars[runes[0]] || allowedSpecialChars[runes[len(runes)-1]] {
|
|
return "", false
|
|
}
|
|
// if runes[0] == '-' || runes[len(runes)-1] == '-' {
|
|
// return "", false
|
|
// }
|
|
|
|
var specialCount uint8
|
|
for _, r := range runes {
|
|
// Check if the character is a whitespace, which is not allowed
|
|
if unicode.IsSpace(r) {
|
|
return "", false
|
|
}
|
|
|
|
// Letters (including any alphabet) and digits are allowed
|
|
if unicode.IsLetter(r) || unicode.IsDigit(r) {
|
|
specialCount = 0
|
|
continue
|
|
}
|
|
|
|
// Combining marks (accents) are allowed
|
|
if unicode.IsMark(r) {
|
|
specialCount = 0
|
|
continue
|
|
}
|
|
|
|
// Check for allowed special characters
|
|
if allowedSpecialChars[r] {
|
|
if specialCount == 2 {
|
|
return "", false
|
|
}
|
|
specialCount++
|
|
continue
|
|
}
|
|
|
|
// If any other character is encountered, return false
|
|
return "", false
|
|
}
|
|
|
|
// Return the trimmed string and true if all conditions are met
|
|
return trimmed, true
|
|
}
|