Advertisement
aldikhan13

EXAMPLE GO CUSTOM VALIDATOR

Apr 27th, 2021 (edited)
1,191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.51 KB | None | 0 0
  1. // NOTED: if value or key is exist in mapping = error
  2. // NOTED: if value or key is not exist in mapping = not error
  3. // more validation struct reference follow this link -> https://github.com/go-playground/validator
  4.  
  5. // example usage
  6. package main
  7.  
  8. import (
  9.     "fmt"
  10.     util "github.com/restuwahyu13/customvalidator/utils"
  11. )
  12.  
  13. type User struct {
  14.     Fullname       string     `validate:"required,lowercase"`
  15.     Email          string     `validate:"required,email"`
  16. }
  17.  
  18. func main() {
  19.     var input User
  20.    
  21.     input.Fullname = "Restu Wahyu Saputra"
  22.     input.Email = "restuwahyu13@#zetmail.com"
  23.  
  24.     resultErr := util.GoValidator(input)
  25.  
  26.     if resultErr["Fullname"] == "" {
  27.       fmt.Println("Fullname is required")
  28.       return
  29.     }
  30.  
  31.     if resultErr["Email"] == "" {
  32.       fmt.Println("Emai is required")
  33.       return
  34.     }
  35.  
  36.     if resultErr["Fullname"] == "Restu Wahyu Saputra" {
  37.       fmt.Println("Fullname must be lowercase not camelcase")
  38.       return
  39.     }
  40.  
  41.     if resultErr["Email"] == "restuwahyu13@#zetmail.com" {
  42.       fmt.Println("Emai is not valid")
  43.       return
  44.     }
  45. }
  46.  
  47. // example custom validator
  48. package util
  49.  
  50. import "github.com/go-playground/validator/v10"
  51.  
  52. var validate *validator.Validate
  53.  
  54. func GoValidator(s interface{}) map[string]interface{} {
  55.  
  56.     validate = validator.New()
  57.  
  58.     err := validate.Struct(s)
  59.     errObject := make(map[string]interface{})
  60.  
  61.     if err != nil {
  62.         for _, errResult := range  err.(validator.ValidationErrors) {
  63.             errObject[errResult.StructField()] = errResult.Value()
  64.         }
  65.     }
  66.  
  67.     return errObject
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement