code
controller
package controllers
import (
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/validation"
)
type ValidController struct {
beego.Controller
}
type User struct {
// 前端的uname首字母是小写的 需要指定
Uname string `form:"uname"`
Pwd string `form:"pwd"`
}
// 关闭ValidController的xsrf保护
func (this *ValidController) Prepare() {
this.EnableXSRF = false
}
func (this *ValidController)Get() {
this.TplName = "validate.html"
}
func (this *ValidController)Post() {
// 把前端form表单的数据解析到自己定义的结构体中
var user User
err := this.ParseForm(&user)
if err != nil {
fmt.Println(err)
return
}
// 校验数据
valid := validation.Validation{}
// 常规校验
valid.Required(user.Uname, "uname").Message("用户名不能为空")
valid.Required(user.Pwd, "pwd").Message("密码不能为空")
if valid.HasErrors() {
for _,val := range valid.Errors {
fmt.Println(val.Key)
fmt.Println(val.Message)
}
this.TplName = "validate.html"