forked from qor/validations
/
validations.go
48 lines (40 loc) · 1.2 KB
/
validations.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package validations
import (
"fmt"
"reflect"
"strings"
"gorm.io/gorm"
)
// NewError generate a new error for a model's field
func NewError(resource interface{}, column, err string) error {
return &Error{Resource: resource, Column: column, Message: err}
}
// Error is a validation error struct that hold model, column and error message
type Error struct {
Resource interface{}
Column string
Message string
}
// Label is a label including model type, primary key and column name
func (err Error) Label() string {
stmt := gorm.Statement{}
stmt.Parse(err.Resource)
var vars = []string{}
for _, field := range stmt.Schema.PrimaryFields {
v, _ := field.ValueOf(reflect.ValueOf(err.Resource))
vars = append(vars, fmt.Sprint(v))
}
return fmt.Sprintf("%v_%v_%v", stmt.Schema.ModelType.Name(), strings.Join(vars, "::"), err.Column)
}
// Error show error message
func (err Error) Error() string {
return fmt.Sprintf("%v", err.Message)
}
// Validator ensures struct has validate functionality.
type Validator interface {
Validate(db *gorm.DB)
}
// ValidatorWithError ensures struct has Validate functionality returns error as validation failure.
type ValidatorWithError interface {
Validate(db *gorm.DB) error
}