Effortless Input Validation in Go with Fiber and go-playground/validator
PART I — Exploring go-playground/validator
Introduction
Data validation is like checking if the keys fit before opening a door. It ensures that the information we get from users is safe and correct. Without it, our websites could become vulnerable to sneaky attacks from hackers. In this blog, we’ll learn how to easily check and handle the information users give us using Go with Fiber and a tool called go-playground/validator.
You can get this code link on github — https://github.com/hrushya07/validations-with-go-fiber (checkout branch — feature/adds-basic-validation)
How to Use Go Validator
Lets install go-validator in project by running following command:
go get -u github.com/go-playground/validator/v10
First will start by adding default validation
That’s it you can see your validation is working as expected, but there is issue with the validation message.
{
"error": {
"field": "Name",
"message": "Key: 'UserRequestBody.Name' Error:Field validation for 'Name' failed on the 'required' tag"
}
}
Hey this is not something we are going to show on our UI. We can add some meaningful messages here. Lets add some default translations
Now you can see the our validations is working as expected with error message as well.
{
"error": {
"field": "Name",
"message": "Name is a required field"
}
}
Lets try to add Custom validation
Will validate email with custom function, now we need add custom function name in validate tag as
Yay! we have added our custom validation to code, but you can notice problem with error message as we encountered previously.
Here as well we need to add translation for our custom validation error message, updated code will look like -
You can explore more more about formatting message on Git Repo.
Wow, there’s a lot of code in the controller file. Let’s tidy it up and make it cleaner. But for this blog post, we’ll stop here. We can continue in the next Part — Streamlining Input Validation in Go with Fiber and go-playground/validator