1. Map 数据校验
package main
import (
"fmt"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/util/gvalid"
)
func main() {
data := g.Map{
"name": "John",
"age": 25,
"email": "john@example.com",
}
rules := []string{
"name@required|min:3|max:20",
"age@required|between:18,60",
"email@required|email",
}
if e := gvalid.CheckMap(data, rules); e != nil {
fmt.Println("Validation failed:")
fmt.Println(e.Map())
} else {
fmt.Println("Validation passed")
}
}
2. 结构体数据校验
package main
import (
"fmt"
"github.com/gogf/gf/util/gvalid"
)
type User struct {
Name string `v:"required|min:3|max:20"`
Age int `v:"required|between:18,60"`
Email string `v:"required|email"`
}
func main() {
user := User{
Name: "John",
Age: 25,
Email: "john@example.com",
}
if e := gvalid.CheckStruct(&user, nil); e != nil {
fmt.Println("Validation failed:")
fmt.Println(e.Map())
} else {
fmt.Println("Validation passed")
}
}
3. JSON 数据校验
package main
import (
"fmt"
"github.com/gogf/gf/util/gvalid"
)
func main() {
jsonData := `{"name":"John","age":25,"email":"john@example.com"}`
rules := []string{
"name@required|min:3|max:20",
"age@required|between:18,60",
"email@required|email",
}
if e := gvalid.CheckString(jsonData, rules); e != nil {
fmt.Println("Validation failed:")
fmt.Println(e.Map())
} else {
fmt.Println("Validation passed")
}
}
这些示例分别演示了对 Map 数据、结构体数据和 JSON 数据的校验。你可以根据具体的场景选择合适的数据对象类型,并使用 gvalid 包中的对应函数进行数据校验。
转载请注明出处:http://www.zyzy.cn/article/detail/7575/GoFrame