@@ -25,6 +25,12 @@ type Address struct {
2525 Phone string `validate:"required"`
2626}
2727
28+ type SignupRequest struct {
29+ Email string `validate:"required,email"`
30+ Password string `validate:"required"`
31+ PasswordConfrim string `validate:"eqfield=Password"`
32+ }
33+
2834// use a single instance of Validate, it caches struct info
2935var validate * validator.Validate
3036
@@ -34,6 +40,7 @@ func main() {
3440
3541 validateStruct ()
3642 validateVariable ()
43+ validateSignup ()
3744}
3845
3946func validateStruct () {
@@ -101,3 +108,42 @@ func validateVariable() {
101108
102109 // email ok, move on
103110}
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