Last active
June 29, 2021 14:12
-
-
Save Siva-Karthi/736d36e21f22ab42bc727629ca3c3441 to your computer and use it in GitHub Desktop.
custom validation go validator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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