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

Viewed 5643

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"
2 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)

The type time.Time is not of a string kind and therefore you cannot do any "string-like" operations on it. That means that you cannot check whether or not it is of some format, and equally you cannot use regular expressions with it.

If you care about the format that is sent by the user you will have to change the type of the field, i.e. DOB string and, if there isn't yet a validator that matches your requirement, you'll have to add a custom validation function because a builtin regex validator was left out by design.

Related