@@ -14,10 +14,24 @@ type Rule struct {
14
14
Error error
15
15
}
16
16
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
+
17
31
// Rules is a slice that contains all validation rules.
18
32
var Rules = []Rule {
19
33
{
20
- Tag : "regexp" ,
34
+ Tag : RegexpTag ,
21
35
Handler : func (field validator.FieldLevel ) bool {
22
36
_ , err := regexp .Compile (field .Field ().String ())
23
37
@@ -26,25 +40,25 @@ var Rules = []Rule{
26
40
Error : fmt .Errorf ("the regexp is invalid" ),
27
41
},
28
42
{
29
- Tag : "username" ,
43
+ Tag : UserNameTag ,
30
44
Handler : func (field validator.FieldLevel ) bool {
31
45
return regexp .MustCompile (`^([a-zA-Z0-9-_.@]){3,30}$` ).MatchString (field .Field ().String ())
32
46
},
33
47
Error : fmt .Errorf ("the username must be between 3 and 30 characters, and can only contain letters, numbers, and the following characters: -_.@" ),
34
48
},
35
49
{
36
- Tag : "password" ,
50
+ Tag : UserPasswordTag ,
37
51
Handler : func (field validator.FieldLevel ) bool {
38
52
return regexp .MustCompile (`^(.){5,30}$` ).MatchString (field .Field ().String ())
39
53
},
40
54
Error : fmt .Errorf ("the password cannot be empty and must be between 5 and 30 characters" ),
41
55
},
42
56
{
43
- Tag : "device_name" ,
57
+ Tag : DeviceNameTag ,
44
58
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 ())
46
60
},
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" ),
48
62
},
49
63
}
50
64
@@ -70,8 +84,8 @@ func New() *Validator {
70
84
}
71
85
72
86
// 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 {
75
89
return false , fmt .Errorf ("invalid variable: %w" , fmt .Errorf ("invalid validation on value %s using tag %s" , value , tag ))
76
90
}
77
91
0 commit comments