Skip to content

Instantly share code, notes, and snippets.

@Siva-Karthi
Last active June 29, 2021 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Siva-Karthi/736d36e21f22ab42bc727629ca3c3441 to your computer and use it in GitHub Desktop.
Save Siva-Karthi/736d36e21f22ab42bc727629ca3c3441 to your computer and use it in GitHub Desktop.
custom validation go validator
package main
import (
"fmt"
"github.com/go-playground/validator"
"regexp"
)
type Student struct {
Name string `json:"name" validate:"omitempty,noSplChars"`
}
func main() {
bob := &Student{
Name: "*^*(&^*&",
}
appValidator := validator.New()
_ = appValidator.RegisterValidation("noSplChars", validateNoSplChars)
err := appValidator.Struct(bob)
if err != nil{
validationErrors := err.(validator.ValidationErrors)
fmt.Println("validationErrors",validationErrors)
}
print("done")
}
func validateNoSplChars(fl validator.FieldLevel) bool {
stringField := fl.Field().String()
regex, _ := regexp.Compile("[a-zA-Z0-9].*$")
result := regex.MatchString(stringField)
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment