validate icon indicating copy to clipboard operation
validate copied to clipboard

[question]全局自定义验证器方法中怎么获取其他字段的值

Open neonyo opened this issue 1 year ago • 2 comments

需要获取其他字段值进行判断

neonyo avatar Jun 26 '24 10:06 neonyo

全局自定义验证器 还不支持 获取到其他字段的值

inhere avatar Jun 27 '24 12:06 inhere

@inhere 可以考虑添加吗?这种场景会存在很多

neonyo avatar Jul 05 '24 09:07 neonyo

@inhere 可以考虑添加吗?这种场景会存在很多

正好我也需要这个特性,所以改了一版,目前暂时用go mod replace替换可以使用。

https://github.com/devhaozi/validate

参考测试用例,自定义验证器的第一个参数设置为data DataFace即可获取其他字段的值。

func TestValidation_Validate(t *testing.T) {
	v := New(M{
		"name": "haozi",
	})
	v.AddValidator("checkName", func(data DataFace, val any) bool {
		name, exist := data.Get("name")
		return name == "haozi" && exist
	})
	v.StringRule("name", "required|checkName")
	assert.True(t, v.Validate())

	v = New(M{
		"age": 2,
	})
	v.AddValidator("checkAge", func(data DataFace, val any) bool {
		age, exist := data.Get("age")
		return age == 2 && exist
	})
	v.StringRule("age", "required|checkAge")
	assert.True(t, v.Validate())
}

devhaozi avatar Mar 04 '25 18:03 devhaozi

@devhaozi 赞👍 可以发个PR 😄

inhere avatar Mar 05 '25 01:03 inhere