Skip to content

Commit

Permalink
function and test
Browse files Browse the repository at this point in the history
  • Loading branch information
Rhyanz46 committed Mar 14, 2024
1 parent a9c4ca0 commit 4a18f94
Show file tree
Hide file tree
Showing 4 changed files with 128 additions and 29 deletions.
103 changes: 81 additions & 22 deletions map_validator/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ func buildMessage(msg string, meta MessageMeta) error {
fieldVar := "${field}"
expectedTypeVar := "${expected_type}"
actualTypeVar := "${actual_type}"
actualLengthVar := "${actual_length}"
expectedMinLengthVar := "${expected_min_length}"
expectedMaxLengthVar := "${expected_max_length}"
if strings.Contains(msg, fieldVar) {
if meta.Field != nil {
v := *meta.Field
Expand All @@ -85,6 +88,24 @@ func buildMessage(msg string, meta MessageMeta) error {
msg = strings.ReplaceAll(msg, actualTypeVar, v.String())
}
}
if strings.Contains(msg, actualLengthVar) {
if meta.ActualLength != nil {
v := *meta.ActualLength
msg = strings.ReplaceAll(msg, actualLengthVar, fmt.Sprintf("%v", v))
}
}
if strings.Contains(msg, expectedMinLengthVar) {
if meta.ExpectedMinLength != nil {
v := *meta.ExpectedMinLength
msg = strings.ReplaceAll(msg, expectedMinLengthVar, fmt.Sprintf("%v", v))
}
}
if strings.Contains(msg, expectedMaxLengthVar) {
if meta.ExpectedMaxLength != nil {
v := *meta.ExpectedMaxLength
msg = strings.ReplaceAll(msg, expectedMaxLengthVar, fmt.Sprintf("%v", v))
}
}
return errors.New(msg)
}

Expand Down Expand Up @@ -454,47 +475,71 @@ func validate(field string, dataTemp map[string]interface{}, validator Rules, da
}

if validator.Min != nil && data != nil {
var isErr bool
var actualLength int
err := errors.New(fmt.Sprintf("the field '%s' should be or greater than %v", field, *validator.Min))
if reflect.String == dataType {
if total := utf8.RuneCountInString(data.(string)); total < *validator.Min {
return nil, errors.New(
fmt.Sprintf("the field '%s' should be or greater than %v character", field, *validator.Min),
)
isErr = true
actualLength = total
}
} else if reflect.Float64 == dataType {
if int(data.(float64)) < *validator.Min {
return nil, errors.New(
fmt.Sprintf("the field '%s' should be or greater than %v", field, *validator.Min),
)
} else if isIntegerFamily(dataType) {
val, _ := strconv.Atoi(fmt.Sprintf("%v", data))
if val < *validator.Min {
isErr = true
actualLength = val
}
} else if reflect.Slice == dataType {
if len(sliceData) < *validator.Min {
return nil, errors.New(
fmt.Sprintf("the field '%s' should be or greater than %v", field, *validator.Min),
)
isErr = true
actualLength = len(sliceData)
}
}

if isErr {
if validator.CustomMsg.OnMin != nil {
return nil, buildMessage(*validator.CustomMsg.OnMin, MessageMeta{
Field: &field,
ExpectedMinLength: SetTotal(*validator.Min),
ActualLength: SetTotal(actualLength),
})
}
return nil, err
}
}

if validator.Max != nil && data != nil {
var isErr bool
var actualLength int
err := errors.New(fmt.Sprintf("the field '%s' should be or lower than %v", field, *validator.Max))
if reflect.String == dataType {
if total := utf8.RuneCountInString(data.(string)); total > *validator.Max {
return nil, errors.New(
fmt.Sprintf("the field '%s' should be or lower than %v character", field, *validator.Max),
)
isErr = true
actualLength = total
}
} else if reflect.Float64 == dataType {
if int(data.(float64)) > *validator.Max {
return nil, errors.New(
fmt.Sprintf("the field '%s' should be or lower than %v", field, *validator.Max),
)
} else if isIntegerFamily(dataType) {
val, _ := strconv.Atoi(fmt.Sprintf("%v", data))
if val > *validator.Max {
isErr = true
actualLength = val
}
} else if reflect.Slice == dataType {
if len(sliceData) > *validator.Max {
return nil, errors.New(
fmt.Sprintf("the field '%s' should be or lower than %v", field, *validator.Max),
)
isErr = true
actualLength = len(sliceData)
}
}

if isErr {
if validator.CustomMsg.OnMax != nil {
return nil, buildMessage(*validator.CustomMsg.OnMax, MessageMeta{
Field: &field,
ExpectedMaxLength: SetTotal(*validator.Max),
ActualLength: SetTotal(actualLength),
})
}
return nil, err
}
}

return data, nil
Expand Down Expand Up @@ -540,6 +585,20 @@ func toMapStringInterface(data interface{}) (map[string]interface{}, error) {
return res, nil
}

func extractInteger(data string) int {
var intStr string
re := regexp.MustCompile("[0-9]+")
resStr := re.FindAllString(data, -1)
for _, val := range resStr {
intStr += val
}
res, err := strconv.Atoi(intStr)
if err != nil {
return 0
}
return res
}

func convertValue(newValue interface{}, kind reflect.Kind, data reflect.Value, pointer bool) error {
errNotSupport := errors.New("not support data")
switch kind {
Expand Down
4 changes: 2 additions & 2 deletions map_validator/functions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func TestValidateStringMaxLength(t *testing.T) {
t.Errorf("Expected error, but got none")
}

expectedError := "the field 'field1' should be or lower than 5 character"
expectedError := "the field 'field1' should be or lower than 5"
if err != nil && err.Error() != expectedError {
t.Errorf("Expected error: %s, got: %v", expectedError, err)
}
Expand All @@ -121,7 +121,7 @@ func TestValidateStringMinLength(t *testing.T) {
t.Errorf("Expected error, but got none")
}

expectedError := "the field 'field1' should be or greater than 5 character"
expectedError := "the field 'field1' should be or greater than 5"
if err != nil && err.Error() != expectedError {
t.Errorf("Expected error: %s, got: %v", expectedError, err)
}
Expand Down
13 changes: 8 additions & 5 deletions map_validator/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@ import (
)

type MessageMeta struct {
Field *string
ExpectedType *reflect.Kind
ActualType *reflect.Kind
Field *string
ExpectedType *reflect.Kind
ActualLength *int
ExpectedMinLength *int
ExpectedMaxLength *int
ActualType *reflect.Kind
}

type EnumField[T any] struct {
Expand All @@ -20,8 +23,8 @@ type CustomMsg struct {
OnTypeNotMatch *string
//OnEnumValueNotMatch *string
//OnNull *string
//OnMax *string
//OnMin *string
OnMax *string
OnMin *string
OnRegexString *string
}

Expand Down
37 changes: 37 additions & 0 deletions test/custom_message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,40 @@ func TestValidTypeNotMatchMessage(t *testing.T) {
t.Errorf("Expected not have error, but got error : %s", err)
}
}

func TestInvalidLengthMessage(t *testing.T) {
payload := map[string]interface{}{"total": 1, "unit": "KG"}
validRole := map_validator.RulesWrapper{
Rules: map[string]map_validator.Rules{
"total": {
Type: reflect.Int,
Max: map_validator.SetTotal(3),
Min: map_validator.SetTotal(2),
CustomMsg: map_validator.CustomMsg{
OnMin: map_validator.SetMessage("The min size allowed is ${expected_min_length}., but your input is ${actual_length}"),
OnMax: map_validator.SetMessage("The max size allowed is ${expected_max_length}., but your input is ${actual_length}"),
},
},
},
}
check, err := map_validator.NewValidateBuilder().SetRules(validRole).Load(payload)
if err != nil {
t.Errorf("Expected not have error, but got error : %s", err)
}
expected := "The min size allowed is 2., but your input is 1"
_, err = check.RunValidate()
if err.Error() != expected {
t.Errorf("Expected %s, but got error : %s", expected, err)
}

payload = map[string]interface{}{"total": 12, "unit": "KG"}
check, err = map_validator.NewValidateBuilder().SetRules(validRole).Load(payload)
if err != nil {
t.Errorf("Expected not have error, but got error : %s", err)
}
expected = "The max size allowed is 3., but your input is 12"
_, err = check.RunValidate()
if err.Error() != expected {
t.Errorf("Expected %s, but got error : %s", expected, err)
}
}

0 comments on commit 4a18f94

Please sign in to comment.