Fix "Custom Validators" example (#2186)

* Update fixed error code from merged commit

According to [this](874dcfa6c4) merged commit.

* Fixed incorrect testing date.

Original testing date incompatible demo require, can't get expect result.
check_in date need NOT AFTER check_out date.
This commit is contained in:
Lin Kao-Yuan 2019-12-18 09:44:33 +08:00 committed by thinkerou
parent 168fa94516
commit aee83e040b
1 changed files with 6 additions and 9 deletions

View File

@ -704,25 +704,22 @@ package main
import ( import (
"net/http" "net/http"
"reflect"
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding" "github.com/gin-gonic/gin/binding"
"gopkg.in/go-playground/validator.v8" "gopkg.in/go-playground/validator.v9"
) )
// Booking contains binded and validated data. // Booking contains binded and validated data.
type Booking struct { type Booking struct {
CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"` CheckIn time.Time `form:"check_in" binding:"required" time_format:"2006-01-02"`
CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"` CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`
} }
func bookableDate( var bookableDate validator.Func = func(fl validator.FieldLevel) bool {
v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, date, ok := fl.Field().Interface().(time.Time)
field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string, if ok {
) bool {
if date, ok := field.Interface().(time.Time); ok {
today := time.Now() today := time.Now()
if today.After(date) { if today.After(date) {
return false return false
@ -756,7 +753,7 @@ func getBookable(c *gin.Context) {
$ curl "localhost:8085/bookable?check_in=2018-04-16&check_out=2018-04-17" $ curl "localhost:8085/bookable?check_in=2018-04-16&check_out=2018-04-17"
{"message":"Booking dates are valid!"} {"message":"Booking dates are valid!"}
$ curl "localhost:8085/bookable?check_in=2018-03-08&check_out=2018-03-09" $ curl "localhost:8085/bookable?check_in=2018-03-10&check_out=2018-03-09"
{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"} {"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}
``` ```