validator icon indicating copy to clipboard operation
validator copied to clipboard

why the items in oneof tag can't include comma.

Open Beaelf opened this issue 1 year ago • 2 comments

  • [x] I have looked at the documentation here first?
  • [x] I have looked at the examples provided that may showcase my question here?

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

I want to limit the status value only to be 'active' or 'active,inactive', but it return panic.

Code sample, to showcase or reproduce:

func TestOneof(t *testing.T) {
	type User struct {
		Status string `validate:"oneof='active' 'inactive,active'"`
	}
	user := User{
		Status: "inactive,active",
	}
	err := validator.New().Struct(user)
	fmt.Println(err)
}

result

=== RUN   TestOneof
--- FAIL: TestOneof (0.00s)
panic: Undefined validation function 'active'' on field 'Status' [recovered]
	panic: Undefined validation function 'active'' on field 'Status'

Beaelf avatar Aug 19 '24 13:08 Beaelf

It also seems impossible to use a datetime format which include a comma, e.g. "Monday, January 2, 2006"

ribrdb avatar Oct 09 '24 23:10 ribrdb

Did you try using the escaped version? Comma is the default separator so you usually need to escape the comma using 0x2C. This is noted in the documentation. The hex code, when used in the validator tag, appears to be case sensitive so 0x2c will not work either (though it won't panic).

For your sample, try:

func TestOneof(t *testing.T) {
	type User struct {
		Status string `validate:"oneof='active' 'inactive0x2Cactive'"`
	}
	user := User{
		Status: "inactive,active",
	}
	err := validator.New().Struct(user)
	fmt.Println(err)
}

wdawson avatar Jan 18 '25 05:01 wdawson