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.
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.