In the previous blog, we had gone over struct validations in golang using validator library. Continuing on, in this blog, we’ll cover custom validations.
Let’s say for the below struct:
type Config struct {
ServerUrl string
AppPort int
}
We could validate our struct with validations
provided by the library like:
import (
"fmt"
"github.com/go-playground/validator"
"strings"
)
func Validate(config Config) bool {
validate := validator.New()
validationErr := validate.Struct(config)
if validationErr != nil {
return false
}
return true
}
Now onto the topic of custom validations.
Say, we want to check whether ServerUrl
field is an HTTPS URL
The straight forward way would be to introduce a function:
func customValidator(config Config) bool {
value :=