Answers for "go validator"

0

go validator example

// 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
}
Posted by: Guest on April-27-2021
0

go validator

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
Posted by: Guest on April-30-2021

Browse Popular Code Answers by Language