feat: add constraints (isodd, iseven)

This commit is contained in:
Simon Vieille 2025-07-22 21:10:33 +02:00
commit 0ad15cc717
Signed by: deblan
GPG key ID: 579388D585F70417
2 changed files with 68 additions and 0 deletions

34
validation/iseven.go Normal file
View file

@ -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
}

34
validation/isodd.go Normal file
View file

@ -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
}