Skip to content

Commit

Permalink
Update to currently fixed (#98)
Browse files Browse the repository at this point in the history
Update fixed 500 err and incorrect testing date & output in demo.
- gin-gonic/gin#2186
- gin-gonic/examples#25
  • Loading branch information
mosdeo authored and thinkerou committed Dec 18, 2019
1 parent dc32d82 commit d68699d
Showing 1 changed file with 8 additions and 11 deletions.
19 changes: 8 additions & 11 deletions content/en/docs/examples/custom-validators.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,24 @@ package main

import (
"net/http"
"reflect"
"time"

"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"gopkg.in/go-playground/validator.v8"
"gopkg.in/go-playground/validator.v9"
)

// Booking contains binded and validated data.
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"`
}

func bookableDate(
v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,
field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,
) bool {
if date, ok := field.Interface().(time.Time); ok {
var bookableDate validator.Func = func(fl validator.FieldLevel) bool {
date, ok := fl.Field().Interface().(time.Time)
if ok {
today := time.Now()
if today.Year() > date.Year() || today.YearDay() > date.YearDay() {
if today.After(date) {
return false
}
}
Expand Down Expand Up @@ -62,8 +59,8 @@ func getBookable(c *gin.Context) {
$ curl "localhost:8085/bookable?check_in=2018-04-16&check_out=2018-04-17"
{"message":"Booking dates are valid!"}

$ curl "localhost:8085/bookable?check_in=2018-03-08&check_out=2018-03-09"
{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}
$ curl "localhost:8085/bookable?check_in=2018-03-10&check_out=2018-03-09"
{"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"}
```

[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way.
Expand Down

0 comments on commit d68699d

Please sign in to comment.