Skip to content

Commit

Permalink
add validation example
Browse files Browse the repository at this point in the history
  • Loading branch information
flycash committed Dec 31, 2021
1 parent db6ce13 commit 9729063
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 2 deletions.
15 changes: 13 additions & 2 deletions httpserver/xsrf/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,8 @@
package main

import (
"html/template"

"github.com/beego/beego/v2/server/web"
"html/template"
)

func main() {
Expand All @@ -28,6 +27,7 @@ func main() {
mc := &MainController{}

web.Router("/xsrfpage", mc, "get:XsrfPage")
web.Router("/xsrfjson", mc, "get:XsrfJSON")
web.Router("/new_message", mc, "post:NewMessage")

web.Run(":8080")
Expand All @@ -43,7 +43,18 @@ func (mc *MainController) XsrfPage() {
mc.TplName = "xsrf.html"
}

func (mc *MainController) XsrfJSON() {
mc.XSRFExpire = 7200
type data struct {
XsrfToken string `json:"xsrfToken"`
}
token := mc.XSRFToken()
mc.Ctx.Output.Header("xsrf", token)
_ = mc.JSONResp(&data{XsrfToken: token})
}

func (mc *MainController) NewMessage() {
mc.CheckXSRFCookie()
v, _ := mc.Input()
mc.Ctx.WriteString("hello" + v.Get("message"))
}
54 changes: 54 additions & 0 deletions validation/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package main

import (
"log"
"strings"

"github.com/beego/beego/v2/core/validation"
)

// Set validation function in "valid" tag
// Use ";" as the separator of multiple functions. Spaces accept after ";"
// Wrap parameters with "()" and separate parameter with ",". Spaces accept after ","
// Wrap regex match with "//"
type user struct {
Id int
Name string `valid:"Required;Match(/^Bee.*/)"` // Name cannot be empty and must have prefix Bee
Age int `valid:"Range(1, 140)"` // 1 <= Age <= 140
Email string `valid:"Email; MaxSize(100)"` // Email must be valid email address and the length must be <= 100
Mobile string `valid:"Mobile"` // Mobile must be valid mobile
IP string `valid:"IP"` // IP must be a valid IPV4 address
Address string `valid:"ChinaAddress"`
}

func (u *user) Valid(v *validation.Validation) {
if strings.Index(u.Name, "admin") != -1 {
// 通过 SetError 设置 Name 的错误信息,HasErrors 将会返回 true
v.SetError("Name", "name should contain word admin")
}
}

func main() {
_ = validation.AddCustomFunc("ChinaAddress", func(v *validation.Validation, obj interface{}, key string) {
addr, ok := obj.(string)
if !ok {
return
}
if !strings.HasPrefix(addr, "China") {
v.AddError(key, "China address only")
}
})
valid := validation.Validation{}
u := user{Name: "Beego", Age: 2, Email: "[email protected]"}
b, err := valid.Valid(&u)
if err != nil {
// handle error
}
if !b {
// validation does not pass
// blabla...
for _, err := range valid.Errors {
log.Println(err.Key, err.Message)
}
}
}

0 comments on commit 9729063

Please sign in to comment.