feat: validate more special chars

This commit is contained in:
Ilia Denisov
2026-02-17 19:36:43 +02:00
parent 1379241967
commit d42cee9df1
3 changed files with 51 additions and 18 deletions
+20 -17
View File
@@ -5,23 +5,16 @@ import (
"unicode"
)
/*
TODO: валидация имён
Произвольные наименования, выбираемые игроком, могут иметь классы кораблей,
планеты, флоты и науки. Имена не могут быть длиннее 30 символов. Символы
могут быть буквами алфавита, цифрами и спецсимволами '!@#$%^*-_=+~()[]{}'.
Спецсимволы не могут находиться в начале или конце имени а так же повторяться
более одного раза подряд.
*/
// Allowed special characters
var allowedSpecialChars = map[rune]bool{
'@': true,
'^': true,
'~': true,
'-': true,
'_': true,
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) {
@@ -40,10 +33,14 @@ func ValidateTypeName(input string) (string, bool) {
}
// Dash cannot be at the beginning or end
if runes[0] == '-' || runes[len(runes)-1] == '-' {
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) {
@@ -52,16 +49,22 @@ func ValidateTypeName(input string) (string, bool) {
// 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
}
+30
View File
@@ -156,6 +156,36 @@ func TestValidateString(t *testing.T) {
expected: "",
ok: false,
},
{
name: "Valid consecutive special chars",
input: "Valid_(special)_Chars",
expected: "Valid_(special)_Chars",
ok: true,
},
{
name: "Too many consecutive special chars",
input: "Too_Many_(special[_]Chars",
expected: "",
ok: false,
},
{
name: "Special char at the beginning",
input: "$pecialString",
expected: "",
ok: false,
},
{
name: "Special char at the end",
input: "SpecialString_",
expected: "",
ok: false,
},
{
name: "All valid special chars",
input: "A@#b$%c^*d-_e=+f~(g)[h]{i}j",
expected: "A@#b$%c^*d-_e=+f~(g)[h]{i}j",
ok: true,
},
}
for _, tt := range tests {