1. Map 数据校验
使用 gvalid.CheckMap 对 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. 结构体数据校验
使用 gvalid.CheckStruct 对结构体数据进行校验:
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 字符串数据校验
使用 gvalid.CheckString 对 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")
}
}
以上示例演示了不同参数类型的数据校验方法。你可以根据具体的应用场景选择合适的方法,进行数据校验。
转载请注明出处:http://www.zyzy.cn/article/detail/7577/GoFrame