v8
How to create custom validator with database usage? For example, I need to check that value is unique across table users within email column
Unique rule. Users is table, Email is column
type CreateUserRequest struct {
Email string `validator:"required,unique=users;email"`
}
Hey @vyuldashev yes there is the validation function is just a function and so can capture outside variables or you can use a method, here are a couple examples:
capture
package main
import (
"fmt"
validator "gopkg.in/go-playground/validator.v9"
)
// MyStruct ..
type MyStruct struct {
String string `validate:"is-awesome"`
}
// use a single instance of Validate, it caches struct info
var validate *validator.Validate
func main() {
myDBHandle := "awesome"
validate = validator.New()
validate.RegisterValidation("is-awesome", func(fl validator.FieldLevel) bool {
return fl.Field().String() == myDBHandle
})
s := MyStruct{String: "awesome"}
err := validate.Struct(s)
if err != nil {
fmt.Printf("Err(s):\n%+v\n", err)
}
s.String = "not awesome"
err = validate.Struct(s)
if err != nil {
fmt.Printf("Err(s):\n%+v\n", err)
}
}
method
package main
import (
"fmt"
validator "gopkg.in/go-playground/validator.v9"
)
// MyStruct ..
type MyStruct struct {
String string `validate:"is-awesome"`
}
// use a single instance of Validate, it caches struct info
var validate *validator.Validate
type myDBAbstraction struct {
db string
}
func (a *myDBAbstraction) ValidateUser(fl validator.FieldLevel) bool {
return fl.Field().String() == a.db
}
func main() {
a := &myDBAbstraction{db: "awesome"}
validate = validator.New()
validate.RegisterValidation("is-awesome", a.ValidateUser)
s := MyStruct{String: "awesome"}
err := validate.Struct(s)
if err != nil {
fmt.Printf("Err(s):\n%+v\n", err)
}
a.db = "not awesome"
err = validate.Struct(s)
if err != nil {
fmt.Printf("Err(s):\n%+v\n", err)
}
}
let me know if that helps :)
@joeybloggs Yes, thank you!
Most helpful comment
Hey @vyuldashev yes there is the validation function is just a function and so can capture outside variables or you can use a method, here are a couple examples:
capture
method
let me know if that helps :)