1

what is the approach to get data(field name) from database within the validator.go?

main.go

package main

import (
    "v/utils"

    "os"

    "github.com/go-playground/validator/v10"
)

func init() {
    env.Load(".env")
}

func main() {
    e := echo.New()

    e.Validator = &utils.CustomValidator{Validator: validator.New()}

    e.Logger.Fatal(e.Start("1234"))
}

validator.go

package utils

import (
    "unicode"
    "unicode/utf8"

    "github.com/go-playground/validator/v10"
)

// CustomValidator is type setting of third party validator
type CustomValidator struct {
    Validator *validator.Validate
}

// Init validator
func (cv *CustomValidator) Init() {
    cv.Validator.RegisterValidation("name", func(fl validator.FieldLevel) bool {
        // ******
        // **Need to fetch the `names` from database and check any duplicate**
        // *******
        return true
    })
}

// Validate Data
func (cv *CustomValidator) Validate(i interface{}) error {
    return cv.Validator.Struct(i)
}
Shawn Yeung
  • 99
  • 1
  • 6
  • 1
    This type of database validation should not be done with the validator package. Validator package is for checking input data validity based on format or value domain, not for database duplication checks. – Burak Serdar Sep 27 '21 at 02:05

0 Answers0