sunfmin/govalidations — pull request #3 by athom (2013-06-18 07:23:43+00:00)
Title: Add MessageSwitcher validator and uniqErrors method

加了两处代码:

1. MessageSwitcher 验证

原因是当出现Name一样但Message不一样的多个Error的Errors, 现有的Custom不够自由, 代码比较冗余,遇到需要查数据库的情况还会导致查询多遍效率低下, 如:

```go
gk.Add(govalidations.Presence(func(object interface{}) interface{} {
return object.(*Group).Slug
}, "Slug", i18n.EMAIL_ADDRESS_CANT_BE_BLANK))

gk.Add(govalidations.Custom(func(object interface{}) bool {
group := object.(*Group)
if group.Slug == "" {
return true
}

return regexp.MustCompile(`^[0-9A-z][0-9A-z\-\_]*[0-9A-z]$`).MatchString(group.Slug)
}, "Slug", i18n.INVALID_SLUG))

gk.Add(govalidations.Custom(func(object interface{}) bool {
group := object.(*Group)
if group.Slug == "" {
return true
}

existingGroup, _ := FindBySlug(db, group.Slug)
return existingGroup == nil || existingGroup.Id == group.Id
}, "Slug", i18n.SLUG_HAS_BEEN_TAKEN_BY_OTHER_GROUP))
```

使用新的Validator之后,可以合并多出代码块:
```go
gk.Add(govalidations.MessageSwitcher(func(object interface{}) (r string) {
group := object.(*Group)
if group.Slug == "" {
return i18n.EMAIL_ADDRESS_CANT_BE_BLANK
}

if !regexp.MustCompile(`^[0-9A-z][0-9A-z\-\_]*[0-9A-z]$`).MatchString(group.Slug) {
return i18n.INVALID_SLUG
}

existingGroup, _ := FindBySlug(db, group.Slug)
if !(existingGroup == nil || existingGroup.Id == group.Id) {
return i18n.SLUG_HAS_BEEN_TAKEN_BY_OTHER_GROUP
}

return
}, "Slug"))
```

2. 去掉重复Error的内部函数.
当程序长到比较复杂, 特别是同事到多个DB做验证的时候, 会出现同个Validated的Errors里面有不少Name和Messsage都一样的Error, 这是候会导致界面弹出N个同样的错误消息.所以在HasErrors调用的时候做了Uniq化.