-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample_custom_constraint_test.go
53 lines (42 loc) · 1.3 KB
/
example_custom_constraint_test.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
49
50
51
52
53
package validation_test
import (
"context"
"errors"
"fmt"
"regexp"
"github.com/muonsoft/validation"
"github.com/muonsoft/validation/it"
"github.com/muonsoft/validation/validator"
)
var ErrNotNumeric = errors.New("not numeric")
type NumericConstraint struct {
matcher *regexp.Regexp
}
// it is recommended to use semantic constructors for constraints.
func IsNumeric() NumericConstraint {
return NumericConstraint{matcher: regexp.MustCompile("^[0-9]+$")}
}
func (c NumericConstraint) ValidateString(ctx context.Context, validator *validation.Validator, value *string) error {
// usually, you should ignore empty values
// to check for an empty value you should use it.NotBlankConstraint
if value == nil || *value == "" {
return nil
}
if c.matcher.MatchString(*value) {
return nil
}
// use the validator to build violation with translations
return validator.CreateViolation(ctx, ErrNotNumeric, "This value should be numeric.")
}
func ExampleValidator_Validate_customConstraint() {
s := "alpha"
err := validator.Validate(
context.Background(),
validation.String(s, it.IsNotBlank(), IsNumeric()),
)
fmt.Println(err)
fmt.Println("errors.Is(err, ErrNotNumeric) =", errors.Is(err, ErrNotNumeric))
// Output:
// violation: "This value should be numeric."
// errors.Is(err, ErrNotNumeric) = true
}