Created
December 30, 2020 21:43
-
-
Save Doarakko/bd7957965a259b7715af1cf347ce0774 to your computer and use it in GitHub Desktop.
validate number of digits by golang validator
This file contains hidden or 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" | |
"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: "[email protected]", | |
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