• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang validation.Validation类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/astaxie/beego/validation.Validation的典型用法代码示例。如果您正苦于以下问题:Golang Validation类的具体用法?Golang Validation怎么用?Golang Validation使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Validation类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Recovery

func (l *LoginController) Recovery() {

	email := l.GetString("email")
	valid := validation.Validation{}
	valid.Email(email, "email")
	if valid.HasErrors() {
		var msg string
		for _, err := range valid.Errors {
			msg += fmt.Sprintf("%s: %s\r", err.Key, err.Message)
		}
		l.Ctx.ResponseWriter.WriteHeader(400)
		l.Data["json"] = &map[string]interface{}{"status": "error", "message": msg}
		l.ServeJson()
		return
	}

	user, _ := rbacModels.UserGetByEmail(email)
	if user.Id == 0 {
		l.Data["json"] = &map[string]interface{}{"status": "error", "message": "Пользователь не найден"}
	} else {
		site_url := beego.AppConfig.String("site_url")
		reset_token, _ := user.GenResetPassToken()
		params := map[string]interface{}{}
		params["user:one-time-login-url"] = fmt.Sprintf("%s/admin/reset?token=%s", site_url, reset_token)
		msg := emailSystem.New()
		msg.Template = "email_password_reset"
		msg.Params = &params
		msg.User = user
		if err := msg.SendMail(); err == nil {
			l.Data["json"] = &map[string]interface{}{"status": "info", "message": "Дальнейшие инструкции высланы на указанный почтовый ящик"}
		}
	}

	l.ServeJson()
}
开发者ID:e154,项目名称:www.novshin.ru,代码行数:35,代码来源:public.go


示例2: 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
}
开发者ID:jango2015,项目名称:go-cms,代码行数:39,代码来源:init.go


示例3: Valid

// Valid ...
func (r *RepTarget) Valid(v *validation.Validation) {
	if len(r.Name) == 0 {
		v.SetError("name", "can not be empty")
	}

	if len(r.Name) > 64 {
		v.SetError("name", "max length is 64")
	}

	if len(r.URL) == 0 {
		v.SetError("endpoint", "can not be empty")
	}

	r.URL = utils.FormatEndpoint(r.URL)

	if len(r.URL) > 64 {
		v.SetError("endpoint", "max length is 64")
	}

	// password is encoded using base64, the length of this field
	// in DB is 64, so the max length in request is 48
	if len(r.Password) > 48 {
		v.SetError("password", "max length is 48")
	}
}
开发者ID:vmware,项目名称:harbor,代码行数:26,代码来源:replication_job.go


示例4: 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
}
开发者ID:thuongdinh,项目名称:beegowebapp,代码行数:27,代码来源:router.go


示例5: 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()
}
开发者ID:nathan-osman,项目名称:pratl,代码行数:35,代码来源:user.go


示例6: 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)
	}

}
开发者ID:kameleon83,项目名称:managIncident,代码行数:60,代码来源:user.go


示例7: 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)
}
开发者ID:Raysmond,项目名称:RaysGo,代码行数:36,代码来源:auth.go


示例8: ResetPassword

//重设密码
func (this *AuthController) ResetPassword() {
	code := this.Ctx.Input.Param(":code")
	user := models.User{}
	if !user.TestActivateCode(code) {
		this.Abort("403")
	}
	this.Data["code"] = code
	this.Data["PageTitle"] = fmt.Sprintf("重设密码 | %s", setting.AppName)
	this.Layout = "layout.html"
	this.TplNames = "reset-password.html"
	valid := validation.Validation{}
	form := ResetPasswordForm{}
	if this.Ctx.Request.Method == "POST" {
		if err := this.ParseForm(&form); err != nil {
			beego.Error(err)
		}
		b, err := valid.Valid(form)
		if err != nil {
			beego.Error(err)
		}
		if b {
			user.SetPassword(form.Password)
			if err := user.Update(); err != nil {
				beego.Error(err)
				this.Abort("500")
			}
			user.ConsumeActivateCode(code)
			this.FlashWrite("notice", "新密码已经生效,请重新登录!")
			this.Redirect("/login", 302)
		} else {
			this.Data["HasError"] = true
			this.Data["errors"] = valid.Errors
		}
	}
}
开发者ID:naokij,项目名称:gotalk,代码行数:36,代码来源:auth.go


示例9: Check

func (u *User) Check(v *validation.Validation) {
	if u.Name == "toukii" && u.Passwd == "1234" {
		v.Clear()
	} else {
		v.SetError("login", "user is abnormal.")
	}
}
开发者ID:everfore,项目名称:fservice,代码行数:7,代码来源:user.go


示例10: Valid

// Valid is the custom validation. It runs only when all the standard validations pass
func (o *Object) Valid(v *validation.Validation) {
	if o.Score == 0 {
		// We have no way to set error code here
		// TODO: fix it in Beego
		v.SetError("Score", "Can not be empty")
	}
}
开发者ID:haibin,项目名称:bapi,代码行数:8,代码来源:object.go


示例11: 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")
				}
			}
		}
	}

}
开发者ID:GeoLyu,项目名称:Gopen,代码行数:61,代码来源:board.go


示例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)
			}
		}
	}
}
开发者ID:lynndotconfig,项目名称:go-blog,代码行数:30,代码来源:manage.go


示例13: Valid

func (model *ResetPwdModel) Valid(v *validation.Validation) {
	// Check if passwords of two times are same.
	if model.Password != model.PasswordRe {
		v.SetError("PasswordRe", "auth.repassword_not_match")
		return
	}
}
开发者ID:thanzen,项目名称:identity,代码行数:7,代码来源:viewmodel.go


示例14: Login

/**
 * 登录
 */
func (this *LoginController) Login() {
	val := validation.Validation{}
	username := this.GetString("username")
	password := this.GetString("password")

	val.Required(username, "username")
	val.Required(password, "password")

	if val.HasErrors() {
		for _, v := range val.Errors {
			this.Ctx.WriteString("<script>alert('" + v.Key + " " + v.Message + "');</script>") //遇到一个错误就可以StopRun了其实,这里只是练习验证模块
		}
		this.StopRun()
	}
	toolbox.Display("u", username)
	toolbox.Display("pa", password)

	password = utils.LoginPassword(password)
	toolbox.Display("paaa", password)

	if user.CheckLogin(username, password) == true {
		this.SetSession("username", username)
		this.Ctx.SetCookie("username", username)
		this.Redirect("/admin", 302)
	} else {
		this.Redirect("/login", 302)
	}
}
开发者ID:xiaoyang2022,项目名称:goBlog,代码行数:31,代码来源:login.go


示例15: ValidForm

func (this *BaseController) ValidForm(form interface{}) bool {

	log.Println("ValidForm")

	valid := validation.Validation{}
	ok, _ := valid.Valid(form)
	if !ok {
		for _, err := range valid.Errors {
			/* set error message */
			slice := strings.Split(err.Key, ".")
			name := slice[0] + "Error"
			message := "valid." + err.Message
			this.Data[name] = i18n.Tr(this.Locale.Lang, message)

			log.Println(name)
			log.Println(message)
			log.Println(this.Locale.Lang)
			log.Println(i18n.Tr(this.Locale.Lang, message))

			return false
		}
	}

	return true
}
开发者ID:codeshredder,项目名称:infoboard,代码行数:25,代码来源:base.go


示例16: 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"
}
开发者ID:Raysmond,项目名称:RaysGo,代码行数:27,代码来源:config.go


示例17: 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

}
开发者ID:sshitaime,项目名称:myblog,代码行数:30,代码来源:admin.go


示例18: 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()
}
开发者ID:nathan-osman,项目名称:pratl,代码行数:30,代码来源:user.go


示例19: 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()
}
开发者ID:cnhans,项目名称:kingdoms,代码行数:33,代码来源:api.go


示例20: Valid

func (form *ResetPwdForm) Valid(v *validation.Validation) {
	// Check if passwords of two times are same.
	if form.Password != form.PasswordRe {
		v.SetError("PasswordRe", "Passwords of two times are not matched.")
		return
	}
}
开发者ID:Raysmond,项目名称:RaysGo,代码行数:7,代码来源:user_form.go



注:本文中的github.com/astaxie/beego/validation.Validation类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang session.NewManager函数代码示例发布时间:2022-05-24
下一篇:
Golang utils.RandomCreateBytes函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap