feat: add constraints (isodd, iseven)
This commit is contained in:
parent
1166579b2a
commit
0ad15cc717
2 changed files with 68 additions and 0 deletions
34
validation/iseven.go
Normal file
34
validation/iseven.go
Normal 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
34
validation/isodd.go
Normal 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
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue