Skip to content

Instantly share code, notes, and snippets.

@Doarakko
Created December 30, 2020 21:43
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 Doarakko/bd7957965a259b7715af1cf347ce0774 to your computer and use it in GitHub Desktop.
Save Doarakko/bd7957965a259b7715af1cf347ce0774 to your computer and use it in GitHub Desktop.
validate number of digits by golang validator
package main
import (
"fmt"
"os"
"strconv"
"github.com/go-playground/validator/v10"
)
func validateNumberOfDigit(fl validator.FieldLevel) bool {
field := fl.Field()
param, err := strconv.Atoi(fl.Param())
if err != nil {
panic(err.Error())
}
v := field.Int()
if v < 0 {
panic("negative number")
}
n := 0
for ; v > 0; v /= 10 {
n += 1
}
return n == param
}
type userCred struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=6,max=15"`
Phone int `json:"phone" validate:"required,numeric,int_len=8"`
}
func main() {
u := userCred{
Email: "xxxx@yyyy.zz",
Password: "abcdefghi",
Phone: 8,
}
validate := *validator.New()
err := validate.RegisterValidation("int_len", validateNumberOfDigit)
if err != nil {
panic(err)
}
err = validate.Struct(&u)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("ok")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment