Validation
What you will learn
By the end of this lesson, you will be able to:
- separate decoding, shape validation, business rules, and database constraints;
- produce stable field-level validation errors;
- validate Unicode text intentionally;
- represent omitted and zero values correctly in partial updates;
- avoid relying on application checks for concurrent uniqueness.
Mental model: validation happens in layers
Different boundaries know different facts:
- Transport: Is the body valid JSON and within the size limit?
- Request shape: Are required fields present and correctly formatted?
- Business rules: Is this operation allowed for the current state and user?
- Storage: Do uniqueness, foreign-key, and integrity constraints still hold when operations race?
Do not force all four jobs into struct tags or one generic validation function.
A request type is not the domain type
type createLessonRequest struct {
Title string `json:"title"`
Description string `json:"description"`
Tags []string `json:"tags"`
}
type CreateLessonCommand struct {
Title string
Description string
Tags []string
}
The transport validates and normalises the request before producing a command. The application service applies rules that require repositories, authenticated identity, or current state.
Return structured field errors
type FieldErrors map[string]string
func (e FieldErrors) Error() string {
return "one or more fields are invalid"
}
func validateCreateLesson(request createLessonRequest) FieldErrors {
errors := FieldErrors{}
title := strings.TrimSpace(request.Title)
if title == "" {
errors["title"] = "Title is required."
} else if utf8.RuneCountInString(title) > 120 {
errors["title"] = "Title must contain at most 120 characters."
}
if len(request.Tags) > 10 {
errors["tags"] = "Use at most 10 tags."
}
if len(errors) == 0 {
return nil
}
return errors
}
len(string) counts bytes. Use rune counts when a rule is defined in Unicode code points. Be aware that one user-perceived grapheme can still contain several code points; product requirements must define what “character” means.
Normalisation is a product decision
Trimming surrounding whitespace is often reasonable. Lowercasing an email domain may be reasonable. Silently lowercasing a display name or rewriting user prose may not be.
Validate after the transformations your system actually promises. Store the canonical form needed for comparison separately when the original presentation must be preserved.
Partial updates need presence information
This type cannot distinguish omitted from explicitly false:
type updateLessonRequest struct {
Published bool `json:"published"`
}
Use a pointer when three states are required:
type updateLessonRequest struct {
Title *string `json:"title"`
Published *bool `json:"published"`
}
nil: field omitted;- pointer to
false: explicitly set false; - pointer to
true: explicitly set true.
For more complex semantics, use a dedicated optional type that also distinguishes JSON null if the contract needs it.
Business validation belongs in the service
func (s *Service) Publish(ctx context.Context, actor UserID, lessonID LessonID) error {
lesson, err := s.repository.Find(ctx, lessonID)
if err != nil {
return fmt.Errorf("find lesson: %w", err)
}
if lesson.OwnerID != actor {
return ErrForbidden
}
if lesson.Title == "" {
return ErrLessonIncomplete
}
return s.repository.MarkPublished(ctx, lessonID)
}
Ownership and current state cannot be decided by JSON tags. The application service has the necessary domain context.
Database constraints are still required
Two requests can both check “this slug is available” and then insert at the same time. A database unique constraint provides the final atomic guarantee.
Translate expected constraint violations into domain errors without exposing driver text. The exact detection mechanism depends on the database and driver.
Common mistakes
- Trusting client-side validation: clients can bypass it, and different clients drift.
- Counting bytes when requirements say characters: non-ASCII input is rejected too early.
- Returning the first field error only: users repeat request/fix cycles unnecessarily.
- Using pointers everywhere: only use presence-aware representations where omission differs from zero.
- Checking uniqueness only in Go: concurrent operations can pass the check together.
- Echoing invalid secret fields in an error: validation responses and logs must not expose secrets.
Practice
Validate a registration request with display name, email, password, and optional marketing consent. Return all safe field errors together. Keep password rules out of logs and add a database unique constraint for the canonical email.
type registerRequest struct {
DisplayName string `json:"display_name"`
Email string `json:"email"`
Password string `json:"password"`
MarketingConsent *bool `json:"marketing_consent"`
}
func validateRegistration(request registerRequest) FieldErrors {
problems := FieldErrors{}
displayName := strings.TrimSpace(request.DisplayName)
email := strings.TrimSpace(request.Email)
if displayName == "" {
problems["display_name"] = "Display name is required."
} else if utf8.RuneCountInString(displayName) > 80 {
problems["display_name"] = "Display name must contain at most 80 characters."
}
if email == "" {
problems["email"] = "Email is required."
} else if _, err := mail.ParseAddress(email); err != nil {
problems["email"] = "Enter a valid email address."
}
if len(request.Password) < 12 {
problems["password"] = "Password must contain at least 12 bytes."
}
if len(problems) == 0 {
return nil
}
return problems
}
Email syntax acceptance is not proof that an address is owned or deliverable; verification is a separate flow. Password policy should follow the application's current security requirements, use an appropriate password-hashing function, and never log the value. A unique index on the chosen canonical email provides the final race-safe duplicate guarantee.
Summary
- Validate syntax, shape, domain rules, and storage invariants at their natural boundaries.
- Define whether text limits count bytes, code points, or user-perceived characters.
- Use presence-aware request fields only when omission differs from a zero value.
- Return stable, safe field errors without leaking sensitive input.
- Use database constraints for invariants that must survive concurrency.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.