Validator: Error when put 0 for required int field

Created on 18 Jul 2017  路  6Comments  路  Source: go-playground/validator

Package version: v9

Issue, Question or Enhancement:

I try to put 0 as value for a required in field and the it says missing required field

Code sample, to showcase or reproduce:

package main

import (
    "fmt"
    "gopkg.in/go-playground/validator.v9"
)

type StockPutForm struct {
    Quantity int `validate:"required"`
}

func main() {
    mystruct := StockPutForm{Quantity:0}
    validate := validator.New()
    err := validate.Struct(mystruct)
    fmt.Println(err)
}

Key: 'StockPutForm.Quantity' Error:Field validation for 'Quantity' failed on the 'required' tag

0 is valid value for int then it should work.

Could you please help.
Thanks.

Most helpful comment

It's also documented in the godocs under the required definition

Yes exists was removed because it was confusing, and functionality merged into required.

Just make your int a pointer and keep using required tag.

All 6 comments

My bad, it's documented.
But as in #142 you removed exists validation
Is there any validation that check if value for field exists regardless of what it is?

It's also documented in the godocs under the required definition

Yes exists was removed because it was confusing, and functionality merged into required.

Just make your int a pointer and keep using required tag.

Just checking in, did you get this all working?

it works.
Thanks

@deankarn
what does it mean by "Just make your int a pointer and keep using required tag."?

@deankarn
what does it mean by "Just make your int a pointer and keep using required tag."?

It means that you should use a pointer to an integer instead of an integer itself.

From:

type Testing struct {
    Delay int `validate:"required"`
}

To:

type Testing struct {
    Delay *int `validate:"required"`
}

That way validate:"required" ensures that the pointer is not nil instead of ensuring the value of the integer is not 0.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

scisci picture scisci  路  5Comments

dkostenko picture dkostenko  路  5Comments

alexyans picture alexyans  路  3Comments

phenrigomes picture phenrigomes  路  5Comments

thaonx picture thaonx  路  3Comments