Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make time maximum validation with ozzo validation in golang

I want to make a maximum input for time with format time like (23:30:00) and the maximum time is (09:30:00), i tried the validation using ozzo validation and i find the function and its call "Date(layout string)"

It is the documentation https://github.com/go-ozzo/ozzo-validation

From the documentation i see that the function Date has Min and Max to check specified range but the problem is i don't know how to fill the arguments. The data type is time.Time.

Here is my code

if err := validation.Validate(c.ReleasedTime, validation.Date("15:04:05").Max(????)); err != nil {
    logger.E(err)
    return shared.NewMultiStringValidationError(shared.HTTPErrorBadRequest, map[string]string{
        "en": "Format date",
        "id": "format tanggal",
    })
}

From there i fill the Max arguments "???" because i still confuse how to fill it. Maybe you all can help me to find the this solution or make this validation using another package, i'll be appreciated. Thank you

like image 285
Akhlaq Khan Avatar asked Oct 26 '25 08:10

Akhlaq Khan


1 Answers

There's an example in the testing code.

You could see it here: https://github.com/go-ozzo/ozzo-validation/blob/master/date_test.go#L71

But when we only need compare hour, so it will be a little hack here.

import (
    "fmt"
    "time"

    validation "github.com/go-ozzo/ozzo-validation/v4"
)

func main() {
    layout := "2006-01-02T15:04:05"
    // this add a base date to hour, so we have a valid time.Time object.
    base := "2020-01-01"
    max, _ := time.Parse(layout, base+"T"+"23:30:00")
    fmt.Println(max)
    r := validation.Date(layout).Max(max)
    fmt.Println(r.Validate(base + "T" + "09:00:00")) // ok
    fmt.Println(r.Validate(base + "T" + "23:40:00")) // this should raise error
}

like image 114
hienduyph Avatar answered Oct 28 '25 23:10

hienduyph



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!