Validation
Nika provides a powerful validation system through the common/validator package, built on top of go-playground/validator.
Setup
package main
import (
"github.com/nika-framework/nika"
"github.com/nika-framework/nika/common/validator"
)
func main() {
app := nika.NewApp()
// Initialize validator and register in DI container
validator.Setup(app)
// Optional: load your own translations and choose where the language comes from.
_ = validator.Configure(validator.Config{
DefaultLanguage: "fr",
TranslationsDir: "translations",
LanguageSource: validator.LanguageSourceHeader,
LanguageKey: "Accept-Language",
})
app.LoadModule(rootModule)
app.Listen(":3000")
}
Defining DTOs
Define your Data Transfer Objects with validation tags:
package dto
type CreateUserDTO struct {
Name string `json:"name" validate:"required,min=3,max=50"`
Email string `json:"email" validate:"required,email"`
Mobile string `json:"mobile" validate:"required,ir_mobile"`
Password string `json:"password" validate:"required,min=8,max=32"`
Age int `json:"age" validate:"required,gte=18"`
Role string `json:"role" validate:"required,oneof=admin user guest"`
}
type UpdateUserDTO struct {
Name string `json:"name" validate:"omitempty,min=3,max=50"`
Email string `json:"email" validate:"omitempty,email"`
}
type GetUserDTO struct {
ID string `uri:"id" validate:"required,objectid"`
}
type ListUsersDTO struct {
Page int `form:"page" validate:"omitempty,gte=1"`
PerPage int `form:"per_page" validate:"omitempty,gte=1,lte=100"`
Search string `form:"search" validate:"omitempty,min=1,max=50"`
}
Validation Helpers
BindAndValidate(c *gin.Context, dto interface{}) bool
Binds the JSON request body and validates the struct. Automatically sends error response on failure:
func (ctrl *UserController) Create(c *gin.Context) {
var dto CreateUserDTO
// Binds JSON body + validates
if !validator.BindAndValidate(c, &dto) {
return // Error response is already sent
}
// dto is validated — proceed with business logic
user := ctrl.service.Create(dto)
response.Create(c, user)
}
BindAndValidateQuery(c *gin.Context, dto interface{}) bool
Binds query parameters and validates:
func (ctrl *UserController) List(c *gin.Context) {
var dto ListUsersDTO
// Binds query params + validates
if !validator.BindAndValidateQuery(c, &dto) {
return
}
users := ctrl.service.FindAll(dto.Page, dto.PerPage, dto.Search)
response.Ok(c, users)
}
BindAndValidateUri(c *gin.Context, dto interface{}) bool
Binds URI path parameters and validates:
func (ctrl *UserController) FindOne(c *gin.Context) {
var dto GetUserDTO
// Binds URI params + validates (e.g., validates ObjectId format)
if !validator.BindAndValidateUri(c, &dto) {
return
}
user := ctrl.service.FindByID(dto.ID)
response.Ok(c, user)
}
ValidateStruct(s interface{}) []FieldError
Validates a struct without binding from request:
Validation Tags
Standard Tags
| Tag | Description | Example |
|---|---|---|
required |
Field must not be empty | validate:"required" |
email |
Must be valid email | validate:"email" |
min |
Minimum length or value | validate:"min=3" |
max |
Maximum length or value | validate:"max=50" |
len |
Exact length | validate:"len=10" |
gt |
Greater than | validate:"gt=0" |
gte |
Greater than or equal | validate:"gte=18" |
lt |
Less than | validate:"lt=100" |
lte |
Less than or equal | validate:"lte=100" |
oneof |
Must be one of values | validate:"oneof=red green blue" |
number |
Must be a number | validate:"number" |
url |
Must be valid URL | validate:"url" |
omitempty |
Skip validation if empty | validate:"omitempty,min=3" |
Custom Tags (Iran)
| Tag | Description | Pattern |
|---|---|---|
ir_mobile |
Iranian mobile number | ^09\d{9}$ |
objectid |
MongoDB ObjectId | ^[a-f0-9]{24}$ |
Custom Validation Rules
Register additional validation rules using validator.Set():
// Register custom validation
err := validator.Set("phone", func(fl validator.FieldLevel) bool {
return regexp.MustCompile(`^\+98\d{10}$`).MatchString(fl.Field().String())
})
// Use in DTO
type ContactDTO struct {
Phone string `json:"phone" validate:"required,phone"`
}
validator.Set() now persists custom rules across later validator.Setup() calls,
so you can register project-level rules once and keep them available.
Localization
Validation and binding errors can be translated per request. The package does
not ship application translation files; pass your catalogs from a Go map, one or
more JSON files, or a directory such as translations/. TranslationsDir can
load both one JSON file per language and split section files per language. If no
localization is configured, request language is read from Accept-Language and
the built-in English fallback messages are used.
Example JSON catalog:
{
"fields": {
"name": "nom",
"first_name": "prénom",
"email": "e-mail",
"age": "âge"
},
"rules": {
"required": "Le champ %s est obligatoire",
"min": "Le champ %s doit être au minimum %s",
"min_string": "Le champ %s doit contenir au moins %s caractères",
"max": "Le champ %s doit être au maximum %s",
"max_string": "Le champ %s doit contenir au maximum %s caractères",
"email": "Le format de %s est invalide",
"oneof": "La valeur de %s doit être l'une des suivantes : %s"
},
"errors": {
"VALIDATION_ERROR": "Les données envoyées ne sont pas valides",
"USER_NOT_FOUND": "Utilisateur introuvable"
},
"binding": {
"empty_body": "Le corps de la requête est vide",
"type_error": "Le champ %s doit être de type %s"
}
}
Field names are matched case- and style-insensitively. For example name
matches Name, and first_name matches FirstName, First_Name, or
FIRST_NAME.
Load translations programmatically:
_ = validator.Configure(validator.Config{
DefaultLanguage: "fr",
Translations: map[string]validator.Catalog{
"fr": {
Fields: map[string]string{
"first_name": "prénom",
},
Errors: map[string]string{
"USER_NOT_FOUND": "Utilisateur introuvable",
},
},
},
})
Or pass JSON files directly to Configure:
_ = validator.Configure(validator.Config{
DefaultLanguage: "fr",
TranslationFiles: map[string]string{
"fr": "translations/fr.json",
"en": "translations/en.json",
},
})
Or load every *.json file in a directory:
_ = validator.Configure(validator.Config{
DefaultLanguage: "fr",
TranslationsDir: "translations",
})
For large applications, split one language into multiple files. The known file
names fields.json, rules.json, errors.json, and binding.json are merged
into their matching catalog sections. Any other file becomes a custom section
with the same name.
`src/translations/fr/fields.json`:
src/translations/fr/user.json:
Load the split directory with the same config field:
_ = validator.Configure(validator.Config{
DefaultLanguage: "fr",
TranslationsDir: "src/translations",
})
Choose where the request language is read from:
// Default behavior: read from the Accept-Language header.
_ = validator.Configure(validator.Config{
TranslationsDir: "translations",
})
// Read from the URL query string, for example /users?lang=fr.
_ = validator.Configure(validator.Config{
TranslationsDir: "translations",
LanguageSource: validator.LanguageSourceQuery,
LanguageKey: "lang",
})
// For custom logic, provide a resolver.
_ = validator.Configure(validator.Config{
TranslationsDir: "translations",
LanguageResolver: func(c *gin.Context) string {
return c.GetHeader("X-Locale")
},
})
Supported language sources are LanguageSourceHeader, LanguageSourceQuery,
LanguageSourceParam, LanguageSourceCookie, and LanguageSourceContext.
When only one language catalog is configured, the validator uses that language as the default and skips request language lookup entirely.
Use the same catalogs anywhere you need a translated string. Translate always
returns a string; if the key is missing, it returns the original key unchanged.
For validation rules, the first argument is treated as a field key and is
translated through the fields section when possible.
required := validator.Translate(c, "rules.required", "name")
minimum := validator.Translate(c, "rules.min", "name", "5")
notFound := validator.Translate(c, "errors.USER_NOT_FOUND")
userCreated := validator.Translate(c, "user.created")
blogPublished := validator.Translate(c, "blog.published")
missing := validator.Translate(c, "errors.UNKNOWN") // returns "errors.UNKNOWN"
Outside a Gin request, pass the language explicitly:
Error Response Format
When validation fails, the helper automatically responds with:
{
"success": false,
"error": {
"code": 422,
"type": "VALIDATION_ERROR",
"message": "Les données envoyées ne sont pas valides",
"details": [
{
"field": "name",
"message": "Le champ nom doit contenir au moins 3 caractères"
},
{
"field": "email",
"message": "Le format de e-mail est invalide"
}
]
}
}
error.type stays machine-readable for clients and tests, while error.message
and validation details can be localized for the end user.
Localized Controller Errors
Controllers can reuse the same catalog for non-validation errors:
func (ctrl *UserController) FindOne(c *gin.Context) {
user, ok := ctrl.service.FindByID(c.Param("id"))
if !ok {
validator.AbortWithError(c, http.StatusNotFound, "USER_NOT_FOUND", nil)
return
}
response.Ok(c, user)
}
If you want to keep using common/response directly, resolve the localized text
with validator.ErrorMessage(c, "USER_NOT_FOUND") and pass it as your details or
custom message.
Injecting Validator Directly
The *validator.Validate instance is registered in the DI container: