https://pkg.go.dev/github.com/go-playground/validator/v10#readme-baked-in-validations
- min 最小
- max 最大
- len 长度限制
- gt 大于
- eq 等于
- ne 不等于
- eqfield 与某个字段值一样
- nefield 与某个字段值不一样
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type UserInfo struct {
UserName string `json:"username" binding:"required,min=4,max=6"`
Age int `json:"age" binding:"gt=18,lte=120"`
Password string `json:"password" binding:"required"`
Password2 string `json:"password2" binding:"required,eqfield=Password"`
}
// 结构体中写json
func validation(c *gin.Context) {
var user UserInfo
err := c.ShouldBindJSON(&user)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
} else {
c.JSON(http.StatusOK, user)
}
}
func main() {
router := gin.Default()
router.POST("/validation", validation)
router.Run("localhost:9999")
}