mirror of
https://gitee.com/johng/gf
synced 2026-06-06 02:25:47 +08:00
add example for package gvalid
This commit is contained in:
14
.example/util/gvalid/config.toml
Normal file
14
.example/util/gvalid/config.toml
Normal file
@ -0,0 +1,14 @@
|
||||
|
||||
|
||||
|
||||
# MySQL.
|
||||
[database]
|
||||
[database.default]
|
||||
link = "mysql:root:12345678@tcp(127.0.0.1:3306)/test"
|
||||
debug = true
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
40
.example/util/gvalid/gvalid_struct_meta.go
Normal file
40
.example/util/gvalid/gvalid_struct_meta.go
Normal file
@ -0,0 +1,40 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/gogf/gf/errors/gerror"
|
||||
"github.com/gogf/gf/frame/g"
|
||||
"github.com/gogf/gf/util/gmeta"
|
||||
)
|
||||
|
||||
type UserCreateReq struct {
|
||||
gmeta.Meta `v:"UserCreateReq"`
|
||||
Name string
|
||||
Pass string
|
||||
}
|
||||
|
||||
func UserCreateReqChecker(ctx context.Context, rule string, value interface{}, message string, data interface{}) error {
|
||||
user := &UserCreateReq{}
|
||||
if v, ok := data.(*UserCreateReq); ok {
|
||||
user = v
|
||||
}
|
||||
// SELECT COUNT(*) FROM `user` WHERE `name` = xxx
|
||||
count, err := g.Model("user").Ctx(ctx).Where("name", user.Name).Count()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
return gerror.Newf(`The name "%s" is already token`, user.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
user := &UserCreateReq{
|
||||
Name: "john",
|
||||
Pass: "123456",
|
||||
}
|
||||
err := g.Validator().RuleFunc("UserCreateReq", UserCreateReqChecker).CheckStruct(user)
|
||||
fmt.Println(err)
|
||||
}
|
||||
@ -1,15 +1,6 @@
|
||||
|
||||
|
||||
"gf.gvalid.required" = "字段不能为空"
|
||||
|
||||
|
||||
"ReuiredUserName" = "Please input user name"
|
||||
"ReuiredUserType" = "Please select user type"
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user