Test Failed
Push — main ( b26c62...faec64 )
by Igor
02:33
created

validation_test.NumericConstraint.Name   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
dl 0
loc 2
rs 10
c 0
b 0
f 0
nop 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:
47
	// violation: This value should be numeric.
48
}
49