go
42 lines · 5 steps
Custom validators in Gin
Register reusable struct-tag validators on Gin's binding engine, safely and exactly once.
Explained by
highlit
1package validators
2
3import (
4 "regexp"
5 "sync"
6 "time"
7
8 "github.com/gin-gonic/gin/binding"
9 "github.com/go-playground/validator/v10"
10)
11
12var (
13 slugPattern = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
14 once sync.Once
15)
16
17func Register() {
18 once.Do(func() {
19 v, ok := binding.Validator.Engine().(*validator.Validate)
20 if !ok {
21 return
22 }
23 v.RegisterValidation("slug", validateSlug)
24 v.RegisterValidation("notpast", validateNotPast)
25 })
26}
27
28func validateSlug(fl validator.FieldLevel) bool {
29 s := fl.Field().String()
30 if s == "" {
31 return true
32 }
33 return slugPattern.MatchString(s)
34}
35
36func validateNotPast(fl validator.FieldLevel) bool {
37 ts, ok := fl.Field().Interface().(time.Time)
38 if !ok {
39 return false
40 }
41 return !ts.Before(time.Now())
42}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Registering validators through sync.Once keeps setup idempotent even if called from multiple init paths.
- 2Custom validators are plain functions that read fl.Field() and return a bool verdict.
- 3Treating an empty string as valid lets you compose a format rule with a separate required rule.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/custom-validators-in-gin-explained-go-2263/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.