validator
validator copied to clipboard
How to validate time.Duration type?
Package version eg. v8, v9:
v10
Question:
Is there any way to validate struct field of time.Duration
type using this library?
The code sample below throws invalid syntax panic:
panic: strconv.ParseInt: parsing "100ms": invalid syntax
Code sample, to showcase or reproduce:
package main
import (
"fmt"
"time"
"github.com/go-playground/validator/v10"
)
type Config struct {
Interval time.Duration `validate:"required,gte=100ms"`
}
func main() {
config := &Config{
Interval: time.Millisecond,
}
validate := validator.New()
err := validate.Struct(config)
if err != nil {
panic(err)
}
fmt.Println(config)
}
Hey @w84thesun
no not currently, but I don't see why it couldn't be added. Thanks for the idea!
It may take me a few weeks to get to this, but happy to accept a PR in the meantime.
Hi @deankarn,
As time.Duration
is an int64
type, I initially thought about adding a custom function to handle time.Duration
but then I noticed that RegisterCustomTypeFunc
doesn't deal with the param, and RegisterValidation
would overwrite the existing validation for tags gte
, gt
etc. Is this correct?
If so, in this case, does it make sense to implement validation for time.Duration
as a special case for int64
?
Hi @elias19r @deankarn
I'm having a similar problem. However, this fix does not seem to work well for Defined type.
type Duration time.Duration
Adding additional handling of textual representations of time's would be an excellent extension to the lte,gte,min, max, etc validation rules. These filters do currently work, but you have to remember that a time.Duration
is an int64 value measured in nanoseconds. Meaning the below doesn't work as expected:
type A struct {
// duration between 1 and 300 seconds
T time.Duration `validate="min=1,max=300"`
}
eg := &A{T: time.Second * 30}
The struct will validate the value to be withing 1 and 300 nanoseconds, and since 1 second is 1000 * 1000 * 1000 Nanoseconds.. To get the requisite validation to work you would need to do min=1000000000,max=300000000000
.