refactored for maintainability
This commit is contained in:
71
internal/validation/integerfield.go
Normal file
71
internal/validation/integerfield.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package validation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type IntField struct {
|
||||
Field
|
||||
Value int
|
||||
}
|
||||
|
||||
func newIntField(key string, g Getter) *IntField {
|
||||
raw := g.Get(key)
|
||||
var val int
|
||||
if raw != "" {
|
||||
var err error
|
||||
val, err = strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
g.AddCheck(newFailedCheck(
|
||||
"Value is not a number",
|
||||
fmt.Sprintf("%s must be an integer: %s provided", key, raw),
|
||||
))
|
||||
}
|
||||
}
|
||||
return &IntField{
|
||||
Value: val,
|
||||
Field: newField(key, g),
|
||||
}
|
||||
}
|
||||
|
||||
// Required enforces a non-zero value
|
||||
func (i *IntField) Required() *IntField {
|
||||
if i.Value == 0 {
|
||||
i.getter.AddCheck(newFailedCheck(
|
||||
"Value cannot be 0",
|
||||
fmt.Sprintf("%s is required", i.Key),
|
||||
))
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
// Optional will skip all validations if value is empty
|
||||
func (i *IntField) Optional() *IntField {
|
||||
if i.Value == 0 {
|
||||
i.optional = true
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
// Max enforces a maxmium value
|
||||
func (i *IntField) Max(max int) *IntField {
|
||||
if i.Value > max && !i.optional {
|
||||
i.getter.AddCheck(newFailedCheck(
|
||||
"Value too large",
|
||||
fmt.Sprintf("%s is too large, max %v", i.Key, max),
|
||||
))
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
// Min enforces a minimum value
|
||||
func (i *IntField) Min(min int) *IntField {
|
||||
if i.Value < min && !i.optional {
|
||||
i.getter.AddCheck(newFailedCheck(
|
||||
"Value too small",
|
||||
fmt.Sprintf("%s is too small, min %v", i.Key, min),
|
||||
))
|
||||
}
|
||||
return i
|
||||
}
|
||||
Reference in New Issue
Block a user