Streamlining Input Validation in Go with Fiber and go-playground/validator

Hrushikesh Pardeshi
TechVerito
Published in
2 min readAug 2, 2024

Part II — Code Refactoring for Cleaner Validation

Introduction

Welcome to Part 2 of adding input validation in Go! In the previous part, we covered the basics of validating user input in Go using Fiber and go-playground/validator. We noticed that our code was getting a bit messy with all the validation checks, making it harder to manage. In this installment, we’re going to tidy things up. If you haven’t read Part 1 yet, we suggest giving it a quick look to get up to speed. In this part, we’ll show you how to clean up and optimise our validation code, making it easier to read and maintain. Let’s get started!

If you have not seen Basic Data Validation you can refer — Effortless Input Validation in Go with Fiber and go-playground/validator Blog

You can get this code link on github — https://github.com/hrushya07/validations-with-go-fiber (checkout branch — feature/refactored-code || develop)

Lets add a wrapper for validator, we can create a validator package

Introduce validator wrapper package

Lets try to crack this code —

  • RegisterEnTranslation — this is nothing but we are setting up our translator and setting a default en translator
  • RegisterValidation — here we are adding our custom validation function
  • RegisterPlainTranslation — just overriding default error message without any message formatting
  • registerMessageFunc — this is also a function to register message for custom validation function
  • messsageTranslatorFunc — this is used to format error message provided by registerMessageFunc
  • RegisterCustomTranslation — this is same as RegisterPlainTranslation but it uses registerMessageFunc, messageTranslatorFunc internally for formatting error messages
  • OverrideErrorTagKey — this function used to get json tag used for key for which error occurred.

Now we can move our validation code to method of UserRequestBody, look how our user model file looks like

Moving validation code as method on request object

Thats it now we can introduce a middleware and move parsing and validating logic over there, lets check middleware file for same

Introducing middleware

and we can place this in route as —

app.Post("/users", middleware.ValidateUserRequestBody, userController.RegisterUser)

Now, as you look at the controller layer, you’ll notice how clean and organised it has become. With our validation logic neatly separated and streamlined, our codebase is easier to understand and maintain.

It will restrict invalid request entering into application

--

--