Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Understanding custom filters #107

Closed
nlandeker opened this issue Oct 19, 2021 · 1 comment
Closed

Understanding custom filters #107

nlandeker opened this issue Oct 19, 2021 · 1 comment
Assignees
Labels
question Further information is requested resolved

Comments

@nlandeker
Copy link

Hello,

I have an issue with custom filter logic. I have written a filer below to uphold some custom logic required for that field, but i have noticed that it has no effect on the field, event tried returning straight -1 for all, with no luck.

v.AddFilter(
		"tip_amount_filter", func(val interface{}) int64 {
			if val != nil {
				log.WithFields(log.Fields{"value": val}).Info("value should be other than nil")
				return int64(val.(float64))
			} else {
				log.WithFields(log.Fields{"value": val}).Info("value should be nil")
				return -1
			}
		},
	)

v.FilterRule("tip_amount", "tip_amount_filter")

What am I doing wrong?

Thanks.

@inhere inhere self-assigned this Oct 19, 2021
@inhere inhere added the question Further information is requested label Oct 19, 2021
@inhere
Copy link
Member

inhere commented Oct 20, 2021

hi @nlandeker

You need to add at least one validation rule, then call Validate() method.

validate/issues_test.go

Lines 556 to 585 in 4ead858

func TestIssue_107(t *testing.T) {
taFilter := func(val interface{}) int64 {
if val != nil {
// log.WithFields(log.Fields{"value": val}).Info("value should be other than nil")
return int64(val.(float64))
} else {
// log.WithFields(log.Fields{"value": val}).Info("value should be nil")
return -1
}
}
v := validate.Map(map[string]interface{}{
"tip_amount": float64(12),
})
v.AddFilter("tip_amount_filter", taFilter)
// method 1:
// v.FilterRule("tip_amount", "tip_amount_filter")
// v.AddRule("tip_amount", "int")
// method 2:
v.StringRule("tip_amount", "int", "tip_amount_filter")
assert.Equal(t, float64(12), v.RawVal("tip_amount"))
// call validate
assert.True(t, v.Validate())
// dump.Println(v.FilteredData())
dump.Println(v.SafeData())
assert.Equal(t, int64(12), v.SafeVal("tip_amount"))
}

image

inhere added a commit that referenced this issue Oct 20, 2021
@inhere inhere closed this as completed Jan 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested resolved
Projects
None yet
Development

No branches or pull requests

2 participants