* fix(binding): Expose validator engine used by the default Validator
- Add func ValidatorEngine for returning the underlying validator engine used
  in the default StructValidator implementation.
- Remove the function RegisterValidation from the StructValidator interface
  which made it immpossible to use a StructValidator implementation without the
  validator.v8 library.
- Update and rename test for registering validation
  Test{RegisterValidation => ValidatorEngine}.
- Update readme and example for registering custom validation.
- Add example for registering struct level validation.
- Add documentation for the following binding funcs/types:
  - Binding interface
  - StructValidator interface
  - Validator instance
  - Binding implementations
  - Default func
* fix(binding): Move validator engine getter inside interface
* docs: rm date cmd from custom validation demo
		
	
		
			
				
	
	
		
			50 lines
		
	
	
		
			1.2 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			50 lines
		
	
	
		
			1.2 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| package main
 | |
| 
 | |
| import (
 | |
| 	"net/http"
 | |
| 	"reflect"
 | |
| 	"time"
 | |
| 
 | |
| 	"github.com/gin-gonic/gin"
 | |
| 	"github.com/gin-gonic/gin/binding"
 | |
| 	"gopkg.in/go-playground/validator.v8"
 | |
| )
 | |
| 
 | |
| type Booking struct {
 | |
| 	CheckIn  time.Time `form:"check_in" binding:"required,bookabledate" 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 {
 | |
| 		today := time.Now()
 | |
| 		if today.Year() > date.Year() || today.YearDay() > date.YearDay() {
 | |
| 			return false
 | |
| 		}
 | |
| 	}
 | |
| 	return true
 | |
| }
 | |
| 
 | |
| func main() {
 | |
| 	route := gin.Default()
 | |
| 
 | |
| 	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
 | |
| 		v.RegisterValidation("bookabledate", bookableDate)
 | |
| 	}
 | |
| 
 | |
| 	route.GET("/bookable", getBookable)
 | |
| 	route.Run(":8085")
 | |
| }
 | |
| 
 | |
| func getBookable(c *gin.Context) {
 | |
| 	var b Booking
 | |
| 	if err := c.ShouldBindWith(&b, binding.Query); err == nil {
 | |
| 		c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
 | |
| 	} else {
 | |
| 		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
 | |
| 	}
 | |
| }
 |