本文整理汇总了Golang中github.com/astaxie/beego/validation.Validation.Valid方法的典型用法代码示例。如果您正苦于以下问题:Golang Validation.Valid方法的具体用法?Golang Validation.Valid怎么用?Golang Validation.Valid使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/astaxie/beego/validation.Validation
的用法示例。
在下文中一共展示了Validation.Valid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Login
// Post implemented login action
func (this *LoginController) Login() {
var (
user models.User
form models.LoginForm
valid validation.Validation
)
if err := this.ParseForm(&form); err != nil {
fmt.Println(err)
} else {
if ok, valid_err := valid.Valid(form); ok && valid_err == nil {
user.Name = form.UserName
//user.Password = helpers.EncryptPassword(form.Password, nil)
has, gerr := models.Engine.Get(&user)
if has && gerr == nil && helpers.ValidatePassword(user.Password, form.Password) {
this.SetSession("username", user.Name)
this.SetSession("userid", int(user.Id))
this.SetSession("userrole", int(user.IRole.Id))
this.SetSession("useremail", user.Email)
this.Redirect("/user/view/"+fmt.Sprintf("%d", user.Id), 302)
}
} else {
for _, e := range valid.Errors {
this.FlashError(e.Key + " : " + e.Message)
}
}
}
this.SaveFlash()
this.Data["Form"] = form
this.Data["Title"] = "Login"
this.TplNames = "auth/login.html"
// this.Redirect("/login", 302)
}
示例2: Test_Valid
func Test_Valid(t *testing.T) {
valid := validation.Validation{}
user := &models.User{Username: "zhangsan", Password: "password"}
b, err := valid.Valid(user)
if err != nil {
// handle error
t.Log(err.Error())
t.Error("Valid Error")
}
if !b {
// validation does not pass
// blabla...
for _, err := range valid.Errors {
t.Log(err.Field + "-" + err.String())
t.Log(err.Key, err.Message)
}
t.Log("ppppp")
for k, v := range valid.ErrorMap() {
t.Log(k, "=", v)
}
t.Error("Valid Error")
}
t.Log("Valid not has errors")
}
示例3: Write
// 글쓰기 //
func (write *BoardController) Write() {
write.Layout = "admin/layout.html"
write.LayoutSections = make(map[string]string)
write.LayoutSections["Header"] = "board/common/header.html"
write.LayoutSections["Footer"] = "board/common/footer.html"
write.TplNames = "board/write.html"
flash := beego.ReadFromRequest(&write.Controller)
if ok := flash.Data["error"]; ok != "" {
write.Data["flash"] = ok
}
o := orm.NewOrm()
o.Using("default")
board := models.Board{}
if err := write.ParseForm(&board); err != nil {
beego.Error("에러발생 : ", err)
} else {
write.Data["boards"] = board
valid := validation.Validation{}
isValid, _ := valid.Valid(board)
if write.Ctx.Input.Method() == "POST" {
if !isValid {
write.Data["Errors"] = valid.ErrorsMap
beego.Error("폼이 에러")
} else {
searchArticle := models.Board{Idx: board.Idx}
beego.Debug("추가된 게시물 : ", board.Idx)
err = o.Read(&searchArticle)
beego.Debug("Err:", err)
flash := beego.NewFlash()
if err == orm.ErrNoRows || err == orm.ErrMissPK {
beego.Debug("Query 내역 : ", board)
id, err := o.Insert(&board)
if err == nil {
msg := fmt.Sprintf("게시글이 다음과 같은 고유번호로 생성되었다 IDX :", id)
beego.Debug(msg)
flash.Notice(msg)
flash.Store(&write.Controller)
} else {
msg := fmt.Sprintf("다음과 같은 이유로 새로운 게시물을 추가할수 없다. 사유 : ", err)
beego.Debug(msg)
flash.Error(msg)
flash.Store(&write.Controller)
}
// 내용을 Insert후 /board 로 리다이렉트
write.Redirect("/board", 302)
} else {
beego.Debug("Article found matching details supplied. Cannot insert")
}
}
}
}
}
示例4: invalidModel
/*
数据对象合法性验证
args:要检验的元素,长度为0,则检验全部元素
*/
func (this *base) invalidModel(m interface{}, args ...interface{}) (data interface{}, invalid bool) {
valid := validation.Validation{}
b, err := valid.Valid(m)
if err != nil {
data = utils.JsonMessage(false, "", err.Error())
invalid = true
return
}
if !b {
var errstr string
//检验元素
if n := len(args); n > 0 {
for _, err := range valid.Errors {
if utils.ListContains(args, err.Key[0:strings.Index(err.Key, ".")]) {
errstr += fmt.Sprintf("%s %s;", err.Key, err.Message)
}
}
} else {
for _, err := range valid.Errors {
errstr += fmt.Sprintf("%s %s;", err.Key, err.Message)
}
}
if errstr == "" {
invalid = false
} else {
data = utils.JsonMessage(false, "", errstr)
invalid = true
}
return
}
return
}
示例5: AddCard
/* 新增武将post */
func (this *ApiController) AddCard() {
//登陆提交的表单
card := &models.Card{}
//数据采集
if err := this.ParseForm(card); err != nil {
this.Data["json"] = -1
this.ServeJson()
this.StopRun()
}
//数据验证
valid := validation.Validation{}
b, _ := valid.Valid(card)
if !b { //验证出错,停止
this.Data["json"] = -2
this.ServeJson()
this.StopRun()
}
//卡牌id是否存在
if card.IdExist(card.Id) {
this.Data["json"] = -3
this.ServeJson()
this.StopRun()
}
//插入新卡牌
card.Insert()
SetAllCards()
//输出
this.Data["json"] = 1
this.ServeJson()
}
示例6: Register
// Register displays the registration form.
func (c *UserController) Register() {
f := &RegisterForm{}
if c.Ctx.Request.Method == "POST" {
if err := c.ParseForm(f); err == nil {
v := validation.Validation{}
b, err := v.Valid(f)
if b && err == nil {
if f.Password == f.Password2 {
u, err := models.NewUser(f.Email, f.Name, f.Password)
if err == nil {
c.SetSession("user_id", u.Id)
c.Redirect(c.URLFor("ChatController.Index"), 302)
return
} else {
c.Data["Error"] = "Unable to complete registration"
}
} else {
c.Data["Error"] = "Passwords don't match"
}
} else {
c.Data["Error"] = "Invalid form input"
}
} else {
c.Data["Error"] = "Unable to parse form"
}
}
c.TplName = "user/register.tpl"
c.Render()
}
示例7: EditUser
func (this *AdminController) EditUser() {
o := orm.NewOrm()
o.Using("default")
usersId, _ := strconv.Atoi(this.Ctx.Input.Param(":id"))
users := models.User{}
flash := beego.NewFlash()
err := o.QueryTable("user").Filter("id", usersId).One(&users)
if err != orm.ErrNoRows {
err := this.ParseForm(&users)
if err != nil {
beego.Error("Impossible de parser. Raison: ", err)
} else {
valid := validation.Validation{}
valid.Required(users.Mail, "mail")
valid.Required(users.Role, "role")
isValid, _ := valid.Valid(users)
if this.Ctx.Input.Method() == "POST" {
if !isValid {
flash.Error("Impossible de mettre à jour l'utilisateur")
flash.Store(&this.Controller)
this.Redirect("/incident-manager/admin/user", 302)
} else {
_, err := o.Update(&users)
if err == nil {
flash.Notice("Utilisateur " + users.Mail + " mis à jour")
flash.Store(&this.Controller)
this.Redirect("/incident-manager/admin/user", 302)
} else {
fmt.Println("erreur")
beego.Debug("Mise à jour Impossible dû a : ", err)
}
}
}
}
this.Redirect("/incident-manager/admin/user", 302)
} else {
flash.Notice("Utilisateur %d n'existe pas", usersId)
flash.Store(&this.Controller)
this.Redirect("/incident-manager/", 302)
}
}
示例8: ConfigPost
func (this *ConfigController) ConfigPost() {
var (
form models.ConfigForm
valid validation.Validation
)
if err := this.ParseForm(&form); err != nil {
fmt.Println(err)
} else {
if ok, ve := valid.Valid(form); ok && ve == nil {
if form.Save() {
this.FlashNotice("Configuration saved successfully.")
} else {
this.FlashError("Configuration saved failed.")
}
} else {
for _, e := range valid.Errors {
this.FlashError(e.Key + " : " + e.Message)
}
}
}
this.SaveFlash()
this.Data["Form"] = form
this.Data["Title"] = "Website configuration"
this.TplNames = "admin/config.html"
}
示例9: Login
// Login attempts to authenticate a user. If successful, they are redirected to
// the list of channels that they can join.
func (c *UserController) Login() {
f := &LoginForm{}
if c.Ctx.Request.Method == "POST" {
if err := c.ParseForm(f); err == nil {
v := validation.Validation{}
b, err := v.Valid(f)
if b && err == nil {
u, err := models.FindUser(f.Email)
if err == nil {
if err := u.Authenticate(f.Password); err == nil {
c.SetSession("user_id", u.Id)
r := c.GetString("redirect")
if r == "" {
r = c.URLFor("ChatController.Index")
}
c.Redirect(r, 302)
return
} else {
c.Data["Error"] = "Invalid password"
}
} else {
c.Data["Error"] = "No account with that email address"
}
} else {
c.Data["Error"] = "Invalid form input"
}
} else {
c.Data["Error"] = "Unable to parse form"
}
}
c.TplName = "user/login.tpl"
c.Render()
}
示例10: InputParamsCheck
/**
* @auther jream.lu
* @intro 入参验证
* @logic
* @todo 返回值
* @meta meta map[string][]string rawMetaHeader
* @data data ...interface{} 切片指针 rawDataBody
* @return 返回 true, metaMap, error
*/
func InputParamsCheck(meta map[string][]string, data ...interface{}) (result Result, err error) {
//MetaHeader check
metaCheckResult, err := MetaHeaderCheck(meta)
if err != nil {
return metaCheckResult, err
}
//DataParams check
valid := validation.Validation{}
for _, val := range data {
is, err := valid.Valid(val)
//日志
//检查参数
if err != nil {
// handle error
log.Println(i18n.Tr(global.Lang, "outputParams.SYSTEMILLEGAL"), err)
}
if !is {
for _, err := range valid.Errors {
log.Println(i18n.Tr(global.Lang, "outputParams.DATAPARAMSILLEGAL"), err.Key, ":", err.Message)
result.MetaCheckResult = nil
result.RequestID = metaCheckResult.MetaCheckResult["request-id"]
result.Message = i18n.Tr(global.Lang, "outputParams.DATAPARAMSILLEGAL") + " " + err.Key + ":" + err.Message
return result, errors.New(i18n.Tr(global.Lang, "outputParams.DATAPARAMSILLEGAL"))
}
}
}
return metaCheckResult, nil
}
示例11: AddLevel
/* 新增关卡post */
func (this *ApiController) AddLevel() {
//登陆提交的表单
level := &models.Level{}
//数据采集
if err := this.ParseForm(level); err != nil {
this.Data["json"] = -1
this.ServeJson()
this.StopRun()
}
//数据验证
valid := validation.Validation{}
b, err := valid.Valid(level)
if err != nil {
// handle error
}
if !b { //验证出错,停止
this.Data["json"] = -2
this.ServeJson()
this.StopRun()
}
//卡牌id是否存在
if level.IdExist(level.Id) {
this.Data["json"] = -3
this.ServeJson()
this.StopRun()
}
//插入新关卡
level.Insert()
//输出
this.Data["json"] = 1
this.ServeJson()
}
示例12: Add
func (manage *ManageController) Add() {
manage.TplNames = "add.tpl"
o := orm.NewOrm()
o.Using("default")
article := models.Article{}
if err := manage.ParseForm(&article); err != nil {
beego.Error("Couldn't parse the form. Reason: ", err)
} else {
manage.Data["Article"] = article
}
if manage.Ctx.Input.Method() == "POST" {
valid := validation.Validation{}
isValid, _ := valid.Valid(article)
if !isValid {
manage.Data["Error"] = valid.ErrorsMap
beego.Error("Form didn't validate.", valid.ErrorsMap)
} else {
id, err := o.Insert(&article)
if err == nil {
msg := fmt.Sprintf("Article inserted with id: ", id)
beego.Debug(msg)
} else {
msg := fmt.Sprintf("Couldn't insert new article. Reason: ", err)
beego.Debug(msg)
}
}
}
}
示例13: processUserPasswordForm
func (this *UserController) processUserPasswordForm(user *models.User) {
valid := validation.Validation{}
userPasswordForm := UserPasswordForm{}
if err := this.ParseForm(&userPasswordForm); err != nil {
beego.Error(err)
}
_, err := valid.Valid(userPasswordForm)
if err != nil {
beego.Error(err)
this.Abort("400")
}
if !user.VerifyPassword(userPasswordForm.CurrentPassword) {
valid.SetError("CurrentPassword", "当前密码错误")
}
if len(valid.Errors) > 0 {
this.Data["UserPasswordFormValidErrors"] = valid.Errors
beego.Trace(fmt.Sprint(valid.Errors))
} else {
user.SetPassword(userPasswordForm.Password)
if err := user.Update(); err != nil {
this.Abort("500")
}
this.FlashWrite("notice", "密码已更新!")
this.Redirect(this.Ctx.Request.RequestURI, 302)
}
}
示例14: validForm
func (this *baseRouter) validForm(form interface{}, names ...string) (bool, map[string]*validation.ValidationError) {
// parse request params to form ptr struct
utils.ParseForm(form, this.Input())
// Put data back in case users input invalid data for any section.
name := reflect.ValueOf(form).Elem().Type().Name()
if len(names) > 0 {
name = names[0]
}
this.Data[name] = form
errName := name + "Error"
// check form once
if this.FormOnceNotMatch() {
return false, nil
}
// Verify basic input.
valid := validation.Validation{}
if ok, _ := valid.Valid(form); !ok {
errs := valid.ErrorMap()
this.Data[errName] = &valid
return false, errs
}
return true, nil
}
示例15: Add
func (this *AticleController) Add() {
var article models.Article
valid := validation.Validation{}
title := this.GetString("title", "")
content := this.GetString("content", "")
typeId, _ := this.GetInt("typeId")
article.Content = content
article.Title = title
article.TypeId = typeId
this.Data["art"] = article
this.GetLayout("admin/edit.tpl")
b, err := valid.Valid(&article)
if err != nil {
beego.Error(err)
}
if !b {
this.Data["err"] = valid.Errors
return
}
models.InsertArt(&article)
types := models.GetAllType()
this.Data["types"] = types
article.Content = ""
article.Title = ""
article.TypeId = -1
this.Data["art"] = article
}