-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidator.go
More file actions
70 lines (58 loc) · 1.27 KB
/
validator.go
File metadata and controls
70 lines (58 loc) · 1.27 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package mobikitgo
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
)
type Validator struct {
locale string
}
type ValidationResult struct {
IsValid bool
Errors map[string]string
}
type Rule interface {
Validate(value interface{}) (bool, string)
}
func NewValidator() *Validator {
return &Validator{
locale: "en", // Default locale
}
}
func (v *Validator) SetLocale(locale string) {
v.locale = locale
}
func (v *Validator) Validate(inputs map[string]interface{}, rules map[string]Rule) ValidationResult {
result := ValidationResult{
IsValid: true,
Errors: make(map[string]string),
}
for field, value := range inputs {
if rule, exists := rules[field]; exists {
valid, message := rule.Validate(value)
if !valid {
result.IsValid = false
result.Errors[field] = message
}
}
}
return result
}
// LoadLocale loads the error messages from the specified locale file
func (v *Validator) LoadLocale(locale string) error {
currentDir, err := os.Getwd()
if err != nil {
return err
}
filePath := filepath.Join(currentDir, "src", "locales", locale+".json")
data, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
var messages map[string]string
if err := json.Unmarshal(data, &messages); err != nil {
return err
}
return nil
}