From 0ad15cc71727e2bf8071a430bbb08f0cc226fdff Mon Sep 17 00:00:00 2001 From: Simon Vieille Date: Tue, 22 Jul 2025 21:10:33 +0200 Subject: [PATCH] feat: add constraints (isodd, iseven) --- validation/iseven.go | 34 ++++++++++++++++++++++++++++++++++ validation/isodd.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 validation/iseven.go create mode 100644 validation/isodd.go diff --git a/validation/iseven.go b/validation/iseven.go new file mode 100644 index 0000000..306cae2 --- /dev/null +++ b/validation/iseven.go @@ -0,0 +1,34 @@ +package validation + +import ( + "strconv" +) + +type IsEven struct { + Message string + TypeErrorMessage string +} + +func NewIsEven() IsEven { + return IsEven{ + Message: "This value is not an even number.", + TypeErrorMessage: "This value can not be processed.", + } +} + +func (c IsEven) Validate(data any) []Error { + errors := []Error{} + + // The constraint should not validate an empty data + if len(NewNotBlank().Validate(data)) == 0 { + i, err := strconv.Atoi(data.(string)) + + if err != nil { + errors = append(errors, Error(c.TypeErrorMessage)) + } else if i%2 != 0 { + errors = append(errors, Error(c.Message)) + } + } + + return errors +} diff --git a/validation/isodd.go b/validation/isodd.go new file mode 100644 index 0000000..d7e3b53 --- /dev/null +++ b/validation/isodd.go @@ -0,0 +1,34 @@ +package validation + +import ( + "strconv" +) + +type IsOdd struct { + Message string + TypeErrorMessage string +} + +func NewIsOdd() IsOdd { + return IsOdd{ + Message: "This value is not a odd number.", + TypeErrorMessage: "This value can not be processed.", + } +} + +func (c IsOdd) Validate(data any) []Error { + errors := []Error{} + + // The constraint should not validate an empty data + if len(NewNotBlank().Validate(data)) == 0 { + i, err := strconv.Atoi(data.(string)) + + if err != nil { + errors = append(errors, Error(c.TypeErrorMessage)) + } else if i%2 != 1 { + errors = append(errors, Error(c.Message)) + } + } + + return errors +}