How to convert string ("1994-01-06") to proper date only value?

I am not able to match the layout strings when I am converting the dates.

When request is coming to the API, I am getting the data from handler (date coming from postman for date_of_birth is: “2001-02-02”), and assigning it to User struct. I want to validate data after it is assigned. When assigning the DateOfBirth to struct, I am executing the function FormatDate in order to format string to time. Once it is formated, the value is: “2002-02-02 00:00:00 +0000 UTC”.

Now, in Ozzo validation, validation.Date(layout string) method expects the same layout as “2002-02-02 00:00:00 +0000 UTC”, and I do not know what this layout is. How to match these two layouts?

func FormatDate(date string) time.Time {
    time1, err := time.Parse("2006-01-02", date)
    if err != nil {
        fmt.Println("Error while parsing date :", err)
    }
    return time1
}
type User struct {
    Id          string    `json:"id"`
    FirstName   string    `json:"first_name"`
    LastName    string    `json:"last_name"`
    Email       string    `json:"email"`
    Password    string    `json:"password"`
    DateOfBirth time.Time `json:"date_of_birth"`
}


func (u User) Validate() error {
    fmt.Println("Date is", &u.DateOfBirth)
    return validation.ValidateStruct(&u,
        validation.Field(&u.FirstName, validation.Required, validation.Length(3, 40)),
        validation.Field(&u.LastName, validation.Required, validation.Length(3, 40)),
        validation.Field(&u.Email, validation.Required, is.Email),
        validation.Field(&u.DateOfBirth, validation.Required, validation.Date("2006-01-02").Min(time.Date(1999, time.Month(2), 22, 0, 0, 0, 0, time.UTC))),
    )
}

Not sure. But have you tried this?

validation.Field(&u.DateOfBirth, validation.Required, validation.Date("2002-02-02 00:00:00 +0000 UTC").Min(time.Date(1999, time.Month(2), 22, 0, 0, 0, 0, time.UTC))),

EDIT:I think you should be validating a string type not time.Time
ref: ozzo-validation/date.go at 34bd5476bd5bb4884aee8252974da4cd4e878a75 · go-ozzo/ozzo-validation · GitHub

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.