-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoc.go
More file actions
69 lines (52 loc) · 1.94 KB
/
doc.go
File metadata and controls
69 lines (52 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
Package govalidate provides struct validation using Go struct tags.
It supports 20+ built-in rules, nested struct validation, slice element
validation, custom rule registration, and JSON field name support —
all with zero external dependencies.
# Quick Start
type User struct {
Name string `json:"name" validate:"required,min=3,max=50"`
Email string `json:"email" validate:"required,email"`
Age int `json:"age" validate:"gte=0,lte=150"`
Password string `json:"password" validate:"required,min=8"`
}
errs := govalidate.Validate(User{Name: "Jo", Email: "bad"})
if errs.HasErrors() {
for _, e := range errs.Errors {
fmt.Printf("%s: %s\n", e.Field, e.Message)
}
}
# Built-in Rules
String: required, min, max, len, email, url, ip, alpha, alphanum,
numeric, lowercase, uppercase, contains, startswith, endswith, oneof,
regex, datetime.
Numeric: min, max, gt, gte, lt, lte.
Slice/Map: min (min items), max (max items), len (exact count).
# Nested Structs
GoValidate automatically recurses into nested structs and reports
errors with dot-notation field names:
type Order struct {
Customer Customer `validate:"required"`
Items []Item `validate:"min=1"`
}
// Error: "customer.name: is required"
// Error: "Items[0].Price: must be > 0"
# Custom Rules
govalidate.RegisterRule("even", func(v reflect.Value, param string) string {
if v.Kind() == reflect.Int && v.Int()%2 != 0 {
return "must be an even number"
}
return ""
})
type Config struct {
Workers int `validate:"even,min=2"`
}
# Error Handling
The [ValidationError] type provides field-level error access:
errs.HasErrors() // any errors?
errs.HasField("email") // specific field?
errs.FieldErrors("email") // all errors for field
errs.Map() // map[string][]string for API responses
errs.Error() // combined error string
*/
package govalidate