validator icon indicating copy to clipboard operation
validator copied to clipboard

How to validate time.Duration type?

Open w84thesun opened this issue 5 years ago • 4 comments

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)
}

w84thesun avatar Feb 19 '20 20:02 w84thesun

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.

deankarn avatar Mar 08 '20 19:03 deankarn

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?

elias19r avatar Jul 22 '20 02:07 elias19r

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

tomtwinkle avatar Mar 30 '22 06:03 tomtwinkle

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.

gwvandesteeg avatar Nov 08 '22 03:11 gwvandesteeg