Skip to content

Commit af87c3f

Browse files
committed
example: demonstrate the process of validating a signup request
1 parent 6c3307e commit af87c3f

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

_examples/simple/main.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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
2935
var validate *validator.Validate
3036

@@ -34,6 +40,7 @@ func main() {
3440

3541
validateStruct()
3642
validateVariable()
43+
validateSignup()
3744
}
3845

3946
func 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

Comments
 (0)