在Revel中进行表单输入验证

huangapple go评论93阅读模式
英文:

Form input Validation in Revel

问题

我正在学习Revel,并使用Validation包对输入进行一些检查。
我想要检查数据库中是否已经存在一个带有"name"的记录(我通过表单从用户那里获取输入),如果存在则返回错误,否则创建一条记录。我能够使用内置的方法(如Required、Maxlen...)验证字段并在HTML中显示错误。但是对于我的自定义检查,我应该将自定义验证器添加到Validation包中,还是有其他方法可以向验证上下文中添加自定义键和错误信息?我找不到如何向错误映射中添加自定义键和消息的方法。谢谢。

英文:

Im learning Revel and using the Validation package to do some checks on input.
I want to see if there already exists a record with a "name" in DB (i get a input from user through a form) and if true return error else create a record. Im am able to validate (with built in methods like Required, Maxlen ...) a field and display the error in HTML. But for my custom check Is adding a custom Validator to the Validation package the way to go or is there a way i can add custom keys and error to the Validation Context. I couldnt find how i can added custom keys and message to the error map. Thanks.

答案1

得分: 2

revel的validators.Validator接口如下所示:

type Validator interface {
    IsSatisfied(interface{}) bool
    DefaultMessage() string
}

*validation.Validation有一个方法:

func (v *Validation) Check(obj interface{}, checks ...Validator) *ValidationResult

*validation.ValidationResult有一个方法:

func (*ValidationResult) Message

将它们整合在一起:

type usernameChecker struct {}

func(u usernameChecker) IsSatisified(i interface{}) bool {
    s, k := i.(string)

    if !k {
        return false
    }

    /* 检查 s 是否存在于数据库中 */
}

func(u usernameChecker) DefaultMessage() string {
    return "用户名已被使用"
}

在你的应用程序中

```go
func (c MyApp) SaveUser(username string) revel.Result {
    c.Validation.Check(username, usernameChecker{}).Message("在失败的情况下更具体或翻译的消息")
}

这是我见过的最糟糕的验证库之一。

英文:

revel's validators.Validator interface looks like this:

type Validator interface {
    IsSatisfied(interface{}) bool
    DefaultMessage() string
}

And *validation.Validation has a method:

func (v *Validation) Check(obj interface{}, checks ...Validator) *ValidationResult

And *validation.ValidationResult has a method:

func (*ValidationResult) Message

Putting that all together:

type usernameChecker struct {}

func(u usernameChecker) IsSatisified(i interface{}) bool {
    s, k := i.(string)

    if !k {
        return false
    }

    /* check if s exists in DB */
}

func(u usernameChecker) DefaultMessage() string {
    return "username already in use"
}

And in your application:

func (c MyApp) SaveUser(username string) revel.Result {
    c.Validation.Check(username, usernameChecker{}).Message("more specific or translated message in case of failure")
}

This is one if not the most badly designed validation library I have ever seen.

huangapple
  • 本文由 发表于 2014年6月9日 09:04:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/24112433.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定