安裝
go get github.com/astaxie/beego/validation
測(cè)試是否安裝成功
go test github.com/astaxie/beego/validation
如果輸出如下則表示成功:

image.png
code
package controllers
import (
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/validation"
)
type ValidController struct {
beego.Controller
}
// 關(guān)閉ValidController的xsrf保護(hù)
func (this *ValidController) Prepare() {
this.EnableXSRF = false
}
func (this *ValidController)Get() {
this.TplName = "validate.html"
}
func (this *ValidController)Post() {
uname :=this.GetString("uname")
pwd :=this.GetString("pwd")
fmt.Println(uname)
fmt.Println(pwd)
valid :=validation.Validation{}
valid.Required(uname,"uname").Message("用戶名不能為空")
valid.Required(pwd,"pwd").Message("密碼不能為空")
// 打印錯(cuò)誤
if valid.HasErrors() {
for _, err := range valid.Errors {
fmt.Println(err.Key)
fmt.Println(err.Message)
}
}
this.TplName = "validate.html"
ruter
beego.Router("/valid", &controllers.ValidController{})
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>validate</title>
</head>
<body>
<h1>這是validate頁(yè)面</h1>
<form action="{{urlfor "ValidController.Post"}}" method="post" >
用戶名:<input type="text" name="uname" id="uname"><br>
密 碼:<input type="password" name="pwd" id="pwd"><br>
<input type="submit" id="btn" value="提交">
</form>
</body>
</html>