本文整理汇总了Golang中github.com/astaxie/beego/validation.Validation.HasErrors方法的典型用法代码示例。如果您正苦于以下问题:Golang Validation.HasErrors方法的具体用法?Golang Validation.HasErrors怎么用?Golang Validation.HasErrors使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/astaxie/beego/validation.Validation
的用法示例。
在下文中一共展示了Validation.HasErrors方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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 = ¶ms
msg.User = user
if err := msg.SendMail(); err == nil {
l.Data["json"] = &map[string]interface{}{"status": "info", "message": "Дальнейшие инструкции высланы на указанный почтовый ящик"}
}
}
l.ServeJson()
}
示例2: 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)
}
}
示例3: TestPost
/* 测试战斗提交表单 */
func (this *ApiController) TestPost() {
//测试提交的表单
valid := validation.Validation{}
valid.Required(this.GetString("my"), "1")
valid.Match(this.GetString("my"), regexp.MustCompile("^[,0-9]+$"), "2")
valid.Required(this.GetString("enemie"), "3")
valid.Match(this.GetString("enemie"), regexp.MustCompile("^[,0-9]+$"), "4")
if valid.HasErrors() { //没有通过验证则退出
return
}
//解析提交的敌我方数据
myArray := strings.Split(this.GetString("my"), ",")
enemieArray := strings.Split(this.GetString("enemie"), ",")
mySlice := make([]string, len(myArray))
enemieSlice := make([]string, len(enemieArray))
for k, v := range myArray {
mySlice[k] = v + ",0,0,0,0,0"
}
for k, v := range enemieArray {
enemieSlice[k] = v + ",0,0,0,0,0"
}
//模拟战斗
index := IndexController{}
result := index.SimulateFight(mySlice, "0;0", enemieSlice, "0;0")
this.Data["json"] = result
this.ServeJson()
}
示例4: Register
//用户注册
func (this *User) Register() {
req := this.ReqJson()
if req != nil {
email := req.Get("email").MustString()
nickName := req.Get("nickName").MustString()
password := req.Get("password").MustString()
valid := validation.Validation{}
valid.Email(email, "email")
valid.MinSize(nickName, 6, "nickNameMin")
valid.MaxSize(nickName, 12, "nickNameMax")
valid.MinSize(password, 6, "passwordMin")
valid.MaxSize(password, 12, "passwordMax")
if valid.HasErrors() {
this.CustomAbort(enum.BadRequest.Code(), enum.BadRequest.Str())
}
err := user.AddUser(email, nickName, password)
if err == nil {
this.RespJson(enum.OK, nil)
} else {
if strings.Contains(err.Error(), "email") {
this.RespJson(enum.EmailAlreadyExist, nil)
} else if strings.Contains(err.Error(), "nickname") {
this.RespJson(enum.NickNameAlreadyExist, nil)
} else {
beego.Error(err)
}
}
}
}
示例5: Valid
func (form *LoginForm) Valid(v *validation.Validation) {
valid := validation.Validation{}
valid.Email(form.Email, "email")
if valid.HasErrors() {
v.SetError("Email", form.Locale.Tr("valid.invalid_email"))
}
}
示例6: ValidateCommonSpecs
func (conf *Config) ValidateCommonSpecs() bool {
valid := validation.Validation{}
//Validate mandatory fields.
valid.Required(conf.configLinux.Version, "Version")
//Version must complient with SemVer v2.0.0
valid.Match(conf.configLinux.Version, regexp.MustCompile("^(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)$"), "Version")
valid.Required(conf.configLinux.Platform.OS, "OS")
valid.Required(conf.configLinux.Platform.Arch, "Platform.Arch")
for _, env := range conf.configLinux.Process.Env {
//If Process defined, env cannot be empty
valid.Required(env, "Process.Env")
}
valid.Required(conf.configLinux.Process.User.UID, "User.UID")
valid.Required(conf.configLinux.Process.User.GID, "User.GID")
valid.Required(conf.configLinux.Root.Path, "Root.Path")
//Iterate over Mount array
for _, mount := range conf.configLinux.Mounts {
//If Mount points defined, it must define these three.
valid.Required(mount.Type, "Mount.Type")
valid.Required(mount.Source, "Mount.Source")
valid.Required(mount.Destination, "Mount.Destination")
}
if valid.HasErrors() {
// validation does not pass
for i, err := range valid.Errors {
fmt.Println(i, err.Key, err.Message)
}
return false
}
return true
}
示例7: Signup
/**
* 登录接收
*/
func (this *UserController) Signup() {
//errmsg := make(map[string]string)
requestEmail := this.GetString("email")
requestPassword := this.GetString("password")
svalid := validation.Validation{}
svalid.Required(requestEmail, "email")
svalid.MaxSize(requestEmail, 40, "email")
svalid.Required(requestPassword, "password")
if svalid.HasErrors() {
for _, err := range svalid.Errors {
//fmt.Println(err.Key, err.Message)
this.showmsg("Error Message", "["+err.Key+"]"+err.Message)
}
}
var user models.User
user.Email = requestEmail
user.Password = models.Md5([]byte(requestPassword))
var Ru models.ReturnUser
Ru = user.Select()
if Ru.Id > 0 {
this.SetSession("nickname", Ru.Nickname)
this.SetSession("email", Ru.Email)
this.SetSession("isadmin", Ru.Isadmin)
this.Redirect("/", 302)
} else {
this.showmsg("Error", "Email OR Password IS WRONG")
}
}
示例8: Login
//用户登录
func (this *User) Login() {
json := this.ReqJson()
if json != nil {
email := json.Get("email").MustString()
password := json.Get("password").MustString()
valid := validation.Validation{}
valid.Email(email, "email")
valid.MinSize(password, 6, "passwordMin")
valid.MaxSize(password, 12, "passwordMax")
if valid.HasErrors() {
this.CustomAbort(enum.BadRequest.Code(), enum.BadRequest.Str())
}
u := user.GetUserByEmail(email)
if u == nil {
//用户不存在
this.RespJson(enum.UserNotExist, nil)
} else if util.Md5(u.Salt+password) != u.Password {
//密码错误
this.RespJson(enum.PasswordIncorrect, nil)
} else {
this.SetSession("uId", u.Id.Hex())
user.SetToken(u.Id, this.StartSession().SessionID()) //using cookie as token
this.RespJson(enum.OK, map[string]interface{}{"url": "/"})
}
}
}
示例9: Login
func (this *UserController) Login() {
if this.Ctx.Input.Method() == "GET" {
if this.GetSession("user") != nil {
this.Redirect("/", 302)
}
this.TplNames = "console/login.html"
return
}
json := this.ReqJson()
email := json.Get("email").MustString()
password := json.Get("password").MustString()
valid := validation.Validation{}
valid.Email(email, "email")
valid.MinSize(password, 6, "passwordMin")
valid.MaxSize(password, 12, "passwordMax")
if valid.HasErrors() {
this.CustomAbort(enum.RespCode.BadRequest.Code(), enum.RespCode.BadRequest.Str())
}
user := user.GetUserByEmail(email)
if user == nil {
//用户不存在
this.RespJson(enum.RespCode.UserNotExist, nil)
} else if util.Md5(user.Salt+password) != user.Password {
//密码错误
this.RespJson(enum.RespCode.PasswordIncorrect, nil)
} else {
this.SetSession("user", user)
this.RespJson(enum.RespCode.OK, map[string]interface{}{"url": "/"})
}
}
示例10: Register
//注册 todo 错误处理的优雅封装
func (this *User) Register() {
reqBody := this.Ctx.Input.RequestBody
reqJson, err := simplejson.NewJson(reqBody)
//非法请求
if err != nil {
this.Abort("400")
}
email := reqJson.Get("email").MustString()
nickname := reqJson.Get("nickname").MustString()
password := reqJson.Get("password").MustString()
valid := validation.Validation{}
valid.Email(email, "email") //邮箱
valid.MinSize(nickname, 5, "nickname") //昵称至少5位
valid.MinSize(password, 6, "password") //密码至少6位
//非法请求
if valid.HasErrors() {
this.Abort("400")
}
enumResult := user.AddUser(email, nickname, password)
fmt.Println(enumResult)
this.Data["json"] = map[string]interface{}{"code": enumResult, "msg": enumResult.String()}
this.ServeJson()
}
示例11: HasErrMsgs
// 报错
func (this *Base) HasErrMsgs(valid validation.Validation) (str string, yes bool) {
if valid.HasErrors() {
yes = true
msg := []string{}
for _, err := range valid.Errors {
msg = append(msg, err.Message)
}
str = strings.Join(msg, "; ")
}
return
}
示例12: ValidCompany
//表单验证
func ValidCompany(m *BCompany) string {
v := validation.Validation{}
v.Required(m.Name, "name").Message("单位名称不能为空")
v.Required(m.Phone, "phone").Message("电话不能为空")
v.Required(m.Address, "address").Message("地址不能为空")
if v.HasErrors() {
// 如果有错误信息,证明验证没通过
return utils.WrapErrors(v.Errors)
}
return ""
}
示例13: ValidUser
//表单验证
func ValidUser(m *BUser) string {
v := validation.Validation{}
v.Required(m.Username, "username").Message("邮箱不能为空")
v.Required(m.Password, "password").Message("密码不能为空")
v.Email(m.Username, "username").Message("邮箱格式不正确")
if v.HasErrors() {
// 如果有错误信息,证明验证没通过
return utils.WrapErrors(v.Errors)
}
return ""
}
示例14: Reset
func (this *MainController) Reset() {
this.activeContent("user/reset")
flash := beego.NewFlash()
u := this.Ctx.Input.Param(":uuid")
o := orm.NewOrm()
o.Using("default")
user := models.AuthUser{Reset_key: u}
err := o.Read(&user, "Reset_key")
if err == nil {
if this.Ctx.Input.Method() == "POST" {
password := this.GetString("password")
password2 := this.GetString("password2")
valid := validation.Validation{}
valid.MinSize(password, 6, "password")
valid.Required(password2, "password2")
if valid.HasErrors() {
errormap := make(map[string]string)
for _, err := range valid.Errors {
errormap[err.Key] = err.Message
}
this.Data["Errors"] = errormap
return
}
if password != password2 {
flash.Error("Passwords don't match")
flash.Store(&this.Controller)
return
}
h := pk.HashPassword(password)
// Convert password hash to string
user.Password = hex.EncodeToString(h.Hash) + hex.EncodeToString(h.Salt)
user.Reset_key = ""
if _, err := o.Update(&user); err != nil {
flash.Error("Internal error")
flash.Store(&this.Controller)
return
}
flash.Notice("Password updated.")
flash.Store(&this.Controller)
this.Redirect("/notice", 302)
}
} else {
flash.Notice("Invalid key.")
flash.Store(&this.Controller)
this.Redirect("/notice", 302)
}
}
示例15: Login
func (c *UserController) Login() {
c.setupView("auth/login")
if c.Ctx.Input.Method() == "POST" {
flash := beego.NewFlash()
username := c.GetString("username")
password := c.GetString("password")
valid := validation.Validation{}
valid.Required(username, "username")
valid.Required(password, "password")
if valid.HasErrors() {
errormap := []string{}
for _, err := range valid.Errors {
errormap = append(errormap, "Validation failed on "+err.Key+": "+err.Message+"\n")
}
flash.Error("Invalid data!")
flash.Store(&c.Controller)
c.Data["Errors"] = errormap
return
}
o := orm.NewOrm()
o.Using("default")
user := &models.AuthUser{
Username: username,
}
err := o.Read(user, "Username")
if err == orm.ErrNoRows {
flash.Error("User not found!")
flash.Store(&c.Controller)
return
}
bcryptErr := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
if bcryptErr != nil {
flash.Error("Wrong password!")
flash.Store(&c.Controller)
return
}
m := make(map[string]interface{})
m["email"] = user.Email
m["username"] = user.Username
m["fullname"] = user.Firstname + " " + user.Lastname
m["timestamp"] = time.Now()
c.SetSession("user", m)
c.Redirect("/nladmin"+c.Ctx.Input.Param(":id"), 302) // go to previous page after login
}
}