1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-22 17:30:56 +00:00

Merge pull request #2852 from Radar8/master

validation: fix ErrorMap, added AddError(key, message)
This commit is contained in:
astaxie 2017-11-19 11:08:31 +08:00 committed by GitHub
commit d352e4abcb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -112,7 +112,7 @@ type Validation struct {
RequiredFirst bool
Errors []*Error
ErrorsMap map[string]*Error
ErrorsMap map[string][]*Error
}
// Clear Clean all ValidationError.
@ -129,7 +129,7 @@ func (v *Validation) HasErrors() bool {
// ErrorMap Return the errors mapped by key.
// If there are multiple validation errors associated with a single key, the
// first one "wins". (Typically the first validation will be the more basic).
func (v *Validation) ErrorMap() map[string]*Error {
func (v *Validation) ErrorMap() map[string][]*Error {
return v.ErrorsMap
}
@ -278,14 +278,35 @@ func (v *Validation) apply(chk Validator, obj interface{}) *Result {
}
}
// Add independent error message for key
func (v *Validation) AddError(key, message string) {
Name := key
Field := ""
parts := strings.Split(key, ".")
if len(parts) == 2 {
Field = parts[0]
Name = parts[1]
}
err := &Error{
Message: message,
Key: key,
Name: Name,
Field: Field,
}
v.setError(err)
}
func (v *Validation) setError(err *Error) {
v.Errors = append(v.Errors, err)
if v.ErrorsMap == nil {
v.ErrorsMap = make(map[string]*Error)
v.ErrorsMap = make(map[string][]*Error)
}
if _, ok := v.ErrorsMap[err.Field]; !ok {
v.ErrorsMap[err.Field] = err
v.ErrorsMap[err.Field] = []*Error{}
}
v.ErrorsMap[err.Field] = append(v.ErrorsMap[err.Field], err)
}
// SetError Set error message for one field in ValidationError