[#3113] added NoDecimal number field option

This commit is contained in:
Gani Georgiev
2023-08-29 18:34:48 +03:00
parent 17974d534e
commit 916c74c218
38 changed files with 222 additions and 140 deletions
+18 -3
View File
@@ -456,21 +456,36 @@ func (o *TextOptions) checkRegex(value any) error {
// -------------------------------------------------------------------
type NumberOptions struct {
Min *float64 `form:"min" json:"min"`
Max *float64 `form:"max" json:"max"`
Min *float64 `form:"min" json:"min"`
Max *float64 `form:"max" json:"max"`
NoDecimals bool `form:"noDecimals" json:"noDecimals"`
}
func (o NumberOptions) Validate() error {
var maxRules []validation.Rule
if o.Min != nil && o.Max != nil {
maxRules = append(maxRules, validation.Min(*o.Min))
maxRules = append(maxRules, validation.Min(*o.Min), validation.By(o.checkNoDecimals))
}
return validation.ValidateStruct(&o,
validation.Field(&o.Min, validation.By(o.checkNoDecimals)),
validation.Field(&o.Max, maxRules...),
)
}
func (o *NumberOptions) checkNoDecimals(value any) error {
v, _ := value.(*float64)
if v == nil || !o.NoDecimals {
return nil // nothing to check
}
if *v != float64(int64(*v)) {
return validation.NewError("validation_no_decimals_constraint", "Decimal numbers are not allowed.")
}
return nil
}
// -------------------------------------------------------------------
type BoolOptions struct {
+30 -8
View File
@@ -485,7 +485,7 @@ func TestSchemaFieldInitOptions(t *testing.T) {
{
schema.SchemaField{Type: schema.FieldTypeNumber},
false,
`{"system":false,"id":"","name":"","type":"number","required":false,"presentable":false,"unique":false,"options":{"min":null,"max":null}}`,
`{"system":false,"id":"","name":"","type":"number","required":false,"presentable":false,"unique":false,"options":{"min":null,"max":null,"noDecimals":false}}`,
},
{
schema.SchemaField{Type: schema.FieldTypeBool},
@@ -1743,8 +1743,12 @@ func TestTextOptionsValidate(t *testing.T) {
}
func TestNumberOptionsValidate(t *testing.T) {
number1 := 10.0
number2 := 20.0
int1 := 10.0
int2 := 20.0
decimal1 := 10.5
decimal2 := 20.5
scenarios := []fieldOptionsScenario{
{
"empty",
@@ -1754,23 +1758,41 @@ func TestNumberOptionsValidate(t *testing.T) {
{
"max - without min",
schema.NumberOptions{
Max: &number1,
Max: &int1,
},
[]string{},
},
{
"max - failure with min",
schema.NumberOptions{
Min: &number2,
Max: &number1,
Min: &int2,
Max: &int1,
},
[]string{"max"},
},
{
"max - success with min",
schema.NumberOptions{
Min: &number1,
Max: &number2,
Min: &int1,
Max: &int2,
},
[]string{},
},
{
"NoDecimal range failure",
schema.NumberOptions{
Min: &decimal1,
Max: &decimal2,
NoDecimals: true,
},
[]string{"min", "max"},
},
{
"NoDecimal range success",
schema.NumberOptions{
Min: &int1,
Max: &int2,
NoDecimals: true,
},
[]string{},
},