go
57 lines · 8 steps
Custom validators and binding in Gin
Register a reusable phone-number rule with Gin's validator and turn binding failures into structured field-level error responses.
Explained by
highlit
1package handlers
2
3import (
4 "net/http"
5 "regexp"
6 "sync"
7
8 "github.com/gin-gonic/gin"
9 "github.com/gin-gonic/gin/binding"
10 "github.com/go-playground/validator/v10"
11)
12
13var (
14 phoneRegex = regexp.MustCompile(`^\+?[1-9]\d{1,14}$`)
15 registerPhone sync.Once
16)
17
18func RegisterValidators() {
19 registerPhone.Do(func() {
20 if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
21 v.RegisterValidation("e164", func(fl validator.FieldLevel) bool {
22 return phoneRegex.MatchString(fl.Field().String())
23 })
24 }
25 })
26}
27
28type CreateContactRequest struct {
29 Name string `json:"name" binding:"required,min=2"`
30 Phone string `json:"phone" binding:"required,e164"`
31 Email string `json:"email" binding:"required,email"`
32}
33
34func CreateContact(c *gin.Context) {
35 var req CreateContactRequest
36 if err := c.ShouldBindJSON(&req); err != nil {
37 var verrs validator.ValidationErrors
38 if errors.As(err, &verrs) {
39 fields := make(map[string]string, len(verrs))
40 for _, fe := range verrs {
41 fields[fe.Field()] = fe.Tag()
42 }
43 c.JSON(http.StatusUnprocessableEntity, gin.H{"errors": fields})
44 return
45 }
46 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
47 return
48 }
49
50 contact, err := contacts.Create(c.Request.Context(), req.Name, req.Phone, req.Email)
51 if err != nil {
52 c.JSON(http.StatusInternalServerError, gin.H{"error": "could not create contact"})
53 return
54 }
55
56 c.JSON(http.StatusCreated, contact)
57}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Registering a custom validation tag once lets every request struct reuse it declaratively via binding tags.
- 2Type-asserting binding errors to validator.ValidationErrors lets you report exactly which fields failed and why.
- 3Distinguishing validation failures from malformed input maps cleanly onto different HTTP status codes.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
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
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 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-and-binding-in-gin-explained-go-e43a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.