@@ -14,10 +14,24 @@ type Rule struct {
1414 Error error
1515}
1616
17+ // Tag is the rule used to validate a variable or a structure's field.
18+ type Tag string
19+
20+ const (
21+ // RegexpTag indicates that the regexp must be valide.
22+ RegexpTag = "regexp"
23+ // UserNameTag contains the rule to validate the user's name.
24+ UserNameTag = "username"
25+ // UserPasswordTag contains the rule to validate the user's password.
26+ UserPasswordTag = "password"
27+ // DeviceNameTag contains the rule to validate the device's name.
28+ DeviceNameTag = "device_name"
29+ )
30+
1731// Rules is a slice that contains all validation rules.
1832var Rules = []Rule {
1933 {
20- Tag : "regexp" ,
34+ Tag : RegexpTag ,
2135 Handler : func (field validator.FieldLevel ) bool {
2236 _ , err := regexp .Compile (field .Field ().String ())
2337
@@ -26,25 +40,25 @@ var Rules = []Rule{
2640 Error : fmt .Errorf ("the regexp is invalid" ),
2741 },
2842 {
29- Tag : "username" ,
43+ Tag : UserNameTag ,
3044 Handler : func (field validator.FieldLevel ) bool {
3145 return regexp .MustCompile (`^([a-zA-Z0-9-_.@]){3,30}$` ).MatchString (field .Field ().String ())
3246 },
3347 Error : fmt .Errorf ("the username must be between 3 and 30 characters, and can only contain letters, numbers, and the following characters: -_.@" ),
3448 },
3549 {
36- Tag : "password" ,
50+ Tag : UserPasswordTag ,
3751 Handler : func (field validator.FieldLevel ) bool {
3852 return regexp .MustCompile (`^(.){5,30}$` ).MatchString (field .Field ().String ())
3953 },
4054 Error : fmt .Errorf ("the password cannot be empty and must be between 5 and 30 characters" ),
4155 },
4256 {
43- Tag : "device_name" ,
57+ Tag : DeviceNameTag ,
4458 Handler : func (field validator.FieldLevel ) bool {
45- return regexp .MustCompile (`^([a-zA-Z0-9_.-] ){1,64}$` ).MatchString (field .Field ().String ())
59+ return regexp .MustCompile (`^([a-zA-Z0-9_-] ){1,64}$` ).MatchString (field .Field ().String ())
4660 },
47- Error : fmt .Errorf ("the device name can only contain `_`, `. ` and alpha numeric characters" ),
61+ Error : fmt .Errorf ("the device name can only contain `_`, `- ` and alpha numeric characters" ),
4862 },
4963}
5064
@@ -70,8 +84,8 @@ func New() *Validator {
7084}
7185
7286// Var validates a variable using a ShellHub validation's tags.
73- func (v * Validator ) Var (value , tag string ) (bool , error ) {
74- if err := v .Validate .Var (value , tag ); err != nil {
87+ func (v * Validator ) Var (value string , tag Tag ) (bool , error ) {
88+ if err := v .Validate .Var (value , string ( tag ) ); err != nil {
7589 return false , fmt .Errorf ("invalid variable: %w" , fmt .Errorf ("invalid validation on value %s using tag %s" , value , tag ))
7690 }
7791
0 commit comments