validator icon indicating copy to clipboard operation
validator copied to clipboard

feature request: Custom time parsing format

Open zsaw opened this issue 2 years ago • 3 comments

Package version eg. v10:

Issue, Question or Enhancement:

Code sample, to showcase or reproduce:

var form struct {
    ExpirtTime time.Time `validate:"required,datetime=2006-01-02"`
}

out

"parsing time \"2006-01-02\" as \"2006-01-02T15:04:05Z07:00\": cannot parse \"\" as \"T\""

zsaw avatar Apr 25 '23 14:04 zsaw

@zsaw try to use this:

type form struct {
    ExpirtTime string `validate:"required,datetime=2006-01-02"`
}

nodivbyzero avatar Jul 11 '24 01:07 nodivbyzero

Hello. Tell me how to validate a line with a time zone? I tried differently.

And why not introduce the type of time.Time instead of a string?

Struct

Request struct {
    ScheduledAt string    `validate:"datetime=2006-01-02T15:04:05Z07:00"`
}

data:

{
  "scheduled_at": "2017-07-14T00:00:00Z +03:00"
}

or

{
  "scheduled_at": "2017-07-14T00:00:00Z+03:00"
}

or

{
  "scheduled_at": "2017-07-14T00:00:00Z+0300"
}

return

 Key: 'Request.ScheduledAt' Error:Field validation for 'ScheduledAt' failed on the 'datetime' tag

MoNSTRiKcom avatar Apr 03 '25 20:04 MoNSTRiKcom

@MoNSTRiKcom Here is the test which covers your cases:

func TestDatetimeWithTZValidation(t *testing.T) {
	tests := []struct {
		value string `validate:"datetime=2006-01-02T15:04:05Z07:00"`
		tag   string
	}{
		{"2017-07-14T00:00:00Z +03:00", `datetime=2006-01-02T15:04:05Z -07:00`},
		{"2017-07-14T00:00:00Z+03:00", `datetime=2006-01-02T15:04:05Z-07:00`},
		{"2017-07-14T00:00:00Z+0300", `datetime=2006-01-02T15:04:05Z-0700`},
	}

	validate := New()

	for i, test := range tests {

		errs := validate.Var(test.value, test.tag)

		if !IsEqual(errs, nil) {
			t.Fatalf("Index: %d datetime failed Error: %s", i, errs)
		}
	}
}

nodivbyzero avatar Apr 07 '25 00:04 nodivbyzero