Skip to content
Snippets Groups Projects
Commit dd6ade21 authored by ko_oler's avatar ko_oler
Browse files

Добавлена общая функция валидации и получения ID/названия сущностей

parent 6ca8b34b
No related branches found
No related tags found
No related merge requests found
package id
import "github.com/rs/xid"
import (
"regexp"
"git.perx.ru/perxis/perxis-go/pkg/errors"
"github.com/rs/xid"
)
const (
IDMaxLength = 64
NameMaxLength = 256
)
var isValidID = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9-_]*$`).MatchString
func GenerateNewID() string {
return xid.New().String()
}
func ValidateID(id string) error {
if len(id) > IDMaxLength {
return errors.New("invalid id: too long (max 64 symbols)")
}
if !isValidID(id) {
return errors.New("invalid id: must begin with latin letters and contain latin letters, numbers or '-', '_'")
}
return nil
}
func ValidateName(name string) error {
if len(name) > NameMaxLength {
return errors.New("invalid name: too long (max 256 symbols)")
}
return nil
}
package id
import "testing"
func TestValidateID(t *testing.T) {
tests := []struct {
name string
id string
wantErr bool
}{
{
"Correct ID #1",
"test",
false,
},
{
"Correct ID #2",
"test_1",
false,
},
{
"Correct ID #3",
"test_1-2",
false,
},
{
"Fail, ID starts with number",
"1test",
true,
},
{
"Fail, ID starts with whitespace",
" test",
true,
},
{
"Fail, ID to long",
"9QoulAlFbIcnQYLSudMistN1IczCWrXUTtN5EgNQJd516DN9UjXYJxieJ1RcsNcs1",
true,
},
{
"Fail, ID with symbols",
"test!_)(&&",
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := ValidateID(tt.id); (err != nil) != tt.wantErr {
t.Errorf("ValidateID() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestValidateName(t *testing.T) {
tests := []struct {
nameTest string
name string
wantErr bool
}{
{
"Correct name #1",
"test",
false,
},
{
"Correct name #2",
"test_1",
false,
},
{
"Correct name #3",
"test_1-2",
false,
},
{
"Fail, name to long",
"ChKRLdvWi0wYYPazuBXrIRtNFy96qGrhBDkuKQNd6N2DPV86IGdXVkeTjWj7qezKreIFUp9IUn03A8WJTTORHkgXAvkPuDVM8tVMcnHbR2hznooJ3gGUsXpn4uXo2QhsviHPyUKmE10GnkCOv9FgAMILNoFVHnIiSHI3cjWlGJglpS9YAMXFB1phOIRF5yol3jmPE7EeU1uZPUw9C2PChuksGsOuJQov07Zom0b13r6wOJv8PZVa4IKmjDDLGKlq1",
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := ValidateName(tt.name); (err != nil) != tt.wantErr {
t.Errorf("ValidateName() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment