@@ -25,6 +25,12 @@ type Address struct {
25
25
Phone string `validate:"required"`
26
26
}
27
27
28
+ type SignupRequest struct {
29
+ Email string `validate:"required,email"`
30
+ Password string `validate:"required"`
31
+ PasswordConfrim string `validate:"eqfield=Password"`
32
+ }
33
+
28
34
// use a single instance of Validate, it caches struct info
29
35
var validate * validator.Validate
30
36
@@ -34,6 +40,7 @@ func main() {
34
40
35
41
validateStruct ()
36
42
validateVariable ()
43
+ validateSignup ()
37
44
}
38
45
39
46
func validateStruct () {
@@ -101,3 +108,42 @@ func validateVariable() {
101
108
102
109
// email ok, move on
103
110
}
111
+
112
+ // validateSignup demonstrates the process of validating a signup request
113
+ // using a predefined struct validation. It creates a sample request with
114
+ // invalid data to showcase error handling and a second request with valid
115
+ // data to ensure successful validation.
116
+ func validateSignup () {
117
+ fmt .Println ("Validate Signup request" )
118
+
119
+ // Create a SignupRequest instance with invalid data
120
+ req := & SignupRequest {
121
+
122
+ Password : "Password123!" ,
123
+ PasswordConfrim : "badpassword" ,
124
+ }
125
+
126
+ // Validate the SignupRequest instance against defined struct validation rules
127
+ err := validate .Struct (req )
128
+ if err != nil {
129
+ // Log the validation failure and the specific error details
130
+ fmt .Printf ("Signup request validation failed: %v\n " , err )
131
+ }
132
+
133
+ // Create a new SignupRequest instance with corrected data
134
+ req = & SignupRequest {
135
+
136
+ Password : "Password123!" ,
137
+ PasswordConfrim : "Password123!" ,
138
+ }
139
+
140
+ // Revalidate the corrected SignupRequest instance
141
+ err = validate .Struct (req )
142
+ if err != nil {
143
+ // If this code path executes, there is an unexpected error, so panic
144
+ panic (0 ) // Should not reach here in normal circumstances
145
+ }
146
+
147
+ // Log successful validation of the signup request
148
+ fmt .Println ("Signup request has been validated" )
149
+ }
0 commit comments