|
1
|
|
|
package validation_test |
|
2
|
|
|
|
|
3
|
|
|
import ( |
|
4
|
|
|
"fmt" |
|
5
|
|
|
"regexp" |
|
6
|
|
|
|
|
7
|
|
|
"github.com/muonsoft/validation" |
|
8
|
|
|
"github.com/muonsoft/validation/it" |
|
9
|
|
|
"github.com/muonsoft/validation/validator" |
|
10
|
|
|
) |
|
11
|
|
|
|
|
12
|
|
|
type NumericConstraint struct { |
|
13
|
|
|
matcher *regexp.Regexp |
|
14
|
|
|
} |
|
15
|
|
|
|
|
16
|
|
|
// it is recommended to use semantic constructors for constraints. |
|
17
|
|
|
func IsNumeric() NumericConstraint { |
|
18
|
|
|
return NumericConstraint{matcher: regexp.MustCompile("^[0-9]+$")} |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
func (c NumericConstraint) SetUp(scope *validation.Scope) error { |
|
22
|
|
|
// you may return errors here on the constraint initialization process |
|
23
|
|
|
return nil |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
func (c NumericConstraint) Name() string { |
|
27
|
|
|
return "NumericConstraint" |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
func (c NumericConstraint) ValidateString(value *string, scope validation.Scope) error { |
|
31
|
|
|
// usually, you should ignore empty values |
|
32
|
|
|
// to check for an empty value you should use it.NotBlankConstraint |
|
33
|
|
|
if value == nil || *value == "" { |
|
34
|
|
|
return nil |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
if c.matcher.MatchString(*value) { |
|
38
|
|
|
return nil |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
// use the scope to build violation with translations |
|
42
|
|
|
return scope.BuildViolation("notNumeric", "This value should be numeric.").GetViolation() |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
func ExampleValidator_Validate_customConstraint() { |
|
46
|
|
|
s := "alpha" |
|
47
|
|
|
|
|
48
|
|
|
err := validator.Validate( |
|
49
|
|
|
validation.String(&s, it.IsNotBlank(), IsNumeric()), |
|
50
|
|
|
) |
|
51
|
|
|
|
|
52
|
|
|
violations := err.(validation.ViolationList) |
|
53
|
|
|
for _, violation := range violations { |
|
54
|
|
|
fmt.Println(violation.Error()) |
|
55
|
|
|
} |
|
56
|
|
|
// Output: |
|
57
|
|
|
// violation: This value should be numeric. |
|
58
|
|
|
} |
|
59
|
|
|
|