Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate a time.Time value using go-playground/validator.v9?

Tags:

go

I have this string that I want to validate on my struct, it is optional.

In the validate area is it possible to validate time.Time? Or if some regex is needed how could I do it in the validate part?

DOB           time.Time          `json:"dob,omitempty" bson:"dob,omitempty" validate:"omitempty"`

It will be passed in by a user via JSON and I wish to confirm that what the user passes in is the correct form:

"2001-03-24T16:21:21.269Z"
like image 382
John Avatar asked Oct 21 '25 09:10

John


1 Answers

Maybe this can help? Here's what I did for my ISO8601 format datetime

CreatedAt           string  `json:"created_at" validate:"ISO8601date"

func IsISO8601Date(fl validator.FieldLevel) bool {
    ISO8601DateRegexString := "^(?:[1-9]\\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)-02-29)T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d{1,9})?(?:Z|[+-][01]\\d:[0-5]\\d)$"
    ISO8601DateRegex := regexp.MustCompile(ISO8601DateRegexString)
  return ISO8601DateRegex.MatchString(fl.Field().String())
}

validate = validator.New()
_ = validate.RegisterValidation("ISO8601date", IsISO8601Date)
like image 197
Johnny Avatar answered Oct 24 '25 08:10

Johnny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!