go validator
// NOTED: if value or key is exist in mapping = error
// NOTED: if value or key is not exist in mapping = not error
// more validation struct reference follow this link -> https://github.com/go-playground/validator
// example usage
package main
import (
"fmt"
util "github.com/restuwahyu13/customvalidator/utils"
)
type User struct {
Fullname string `validate:"required,lowercase"`
Email string `validate:"required,email"`
}
func main() {
var input User
input.Fullname = "Restu Wahyu Saputra"
input.Email = "restuwahyu13@#zetmail.com"
resultErr := util.GoValidator(input)
if resultErr["Fullname"] == "" {
fmt.Println("Fullname is required")
return
}
if resultErr["Email"] == "" {
fmt.Println("Emai is required")
return
}
if resultErr["Fullname"] == "Restu Wahyu Saputra" {
fmt.Println("Fullname must be lowercase not camelcase")
return
}
if resultErr["Email"] == "restuwahyu13@#zetmail.com" {
fmt.Println("Emai is not valid")
return
}
}
// example custom validator
package util
import "github.com/go-playground/validator/v10"
var validate *validator.Validate
func GoValidator(s interface{}) map[string]interface{} {
validate = validator.New()
err := validate.Struct(s)
errObject := make(map[string]interface{})
if err != nil {
for _, errResult := range err.(validator.ValidationErrors) {
errObject[errResult.StructField()] = errResult.Value()
}
}
return errObject
}
4.33
3
go-playground-converter is formatter error response
inspiration like express-validator in nodejs
build on top go-playground-validator.
https://github.com/restuwahyu13/go-playground-converter
Thank you!
3
0
Are there any code examples left?
New code examples in category Other
-
Other 2023-03-27 22:50:10 how to select the whole line in vscode with keyboard shortcut
-
Other 2022-03-27 22:45:24 income of a web developer
-
Other 2022-03-27 22:35:01 \pyrcc_main.py: File does not exist 'resources.qrc'
-
Other 2022-03-27 22:30:45 rick roll embed code
-
Other 2022-03-27 22:20:08 Circuit_04_Potentiometer
-
Other 2022-03-27 22:20:05 iterative power
-
Other 2022-03-27 22:15:11 flutter run all
-
Other 2022-03-27 22:10:05 when is karlson release
-
Other 2022-03-27 22:10:02 wp .htaccess example
-
Other 2022-03-27 22:00:08 bash pause in file read line by line