Total Lines | 45 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | package validation_test |
||
2 | |||
3 | import ( |
||
4 | "context" |
||
5 | "fmt" |
||
6 | "regexp" |
||
7 | |||
8 | "github.com/muonsoft/validation" |
||
9 | "github.com/muonsoft/validation/it" |
||
10 | "github.com/muonsoft/validation/validator" |
||
11 | ) |
||
12 | |||
13 | type NumericConstraint struct { |
||
14 | matcher *regexp.Regexp |
||
15 | } |
||
16 | |||
17 | // it is recommended to use semantic constructors for constraints. |
||
18 | func IsNumeric() NumericConstraint { |
||
19 | return NumericConstraint{matcher: regexp.MustCompile("^[0-9]+$")} |
||
20 | } |
||
21 | |||
22 | func (c NumericConstraint) ValidateString(value *string, scope validation.Scope) error { |
||
23 | // usually, you should ignore empty values |
||
24 | // to check for an empty value you should use it.NotBlankConstraint |
||
25 | if value == nil || *value == "" { |
||
26 | return nil |
||
27 | } |
||
28 | |||
29 | if c.matcher.MatchString(*value) { |
||
30 | return nil |
||
31 | } |
||
32 | |||
33 | // use the scope to build violation with translations |
||
34 | return scope.CreateViolation("notNumeric", "This value should be numeric.") |
||
35 | } |
||
36 | |||
37 | func ExampleValidator_Validate_customConstraint() { |
||
38 | s := "alpha" |
||
39 | |||
40 | err := validator.Validate( |
||
41 | context.Background(), |
||
42 | validation.String(s, it.IsNotBlank(), IsNumeric()), |
||
43 | ) |
||
44 | |||
45 | fmt.Println(err) |
||
46 | // Output: |
||
49 |