Description

How to reproduce

package main

import (
    "github.com/gin-gonic/gin"
)

func main() {
    var request struct {
        IsDefault bool `json:"is_default" binding:"required"`
    }
    g := gin.Default()
    g.POST("/", func(c *gin.Context) {
        err := c.ShouldBind(&request)
        if err != nil {
            c.JSON(400, gin.H{
                "message": err.Error(),
            })
            return
        }
        c.JSON(200, gin.H{
            "message": "ok",
        })
    })
    g.Run(":9000")
}


Expectations

$ curl -H "Content-Type: application/json" -X POST --data '{"is_default":false}' http://localhost:9000
{"message":"Key: 'IsDefault' Error:Field validation for 'IsDefault' failed on the 'required' tag"}

Actual result

actually, it's excepted to be 'ok', bug validator return an error, the required tag should only check if form has 'is_default' but not check if it's false

Environment

  • go version: 1.20.1
  • gin version (or commit ref):github.com/gin-gonic/gin v1.9.1
  • operating system: MacOS

Comment From: Yeuoly

I am clear that remove required tag would fix it, but in my view, it's a bug

Comment From: zanmato

You can use *bool if you want to force your users to post is_default

Comment From: Yeuoly

yes it's a way to solve this problem, but as a developer who are new into gin, It's confusing

Comment From: zanmato

It's because of required comparing with the types' empty value, and the empty value for a bool is false. You'd have the same issue if is_default was an int and you passed 0, because 0 is the empty value of an int.

Comment From: Yeuoly

thanks for your explanation! looks like it's a problem related to a more fundamental reason. can we just make it less confusing? maybe I can provide a PR to solve this.

Comment From: zanmato

It's already documented here https://github.com/gin-gonic/gin/blob/master/docs/doc.md#model-binding-and-validation

You can also specify that specific fields are required. If a field is decorated with binding:"required" and has an empty value when binding, an error will be returned.

Use pointers if you want it to work like you were thinking it works, because the empty value of a pointer is nil

Comment From: Yeuoly

Thanks! It’s helpful!

2023年9月22日 22:47,Andreas Johansson @.***> 写道:

It's already documented here https://github.com/gin-gonic/gin/blob/master/docs/doc.md#model-binding-and-validation

You can also specify that specific fields are required. If a field is decorated with binding:"required" and has an empty value when binding, an error will be returned.

Use pointers if you want it to work like you were thinking it works, because the empty value of a pointer is nil

— Reply to this email directly, view it on GitHub https://github.com/gin-gonic/gin/issues/3740#issuecomment-1731551097, or unsubscribe https://github.com/notifications/unsubscribe-auth/AK4YMAEJYFKU5RDJXRWB3J3X3WQINANCNFSM6AAAAAA5CVLXCA. You are receiving this because you authored the thread.