I already have a struct declared as
type User struct {
ID int `json:"id"`
Email string `json:"email"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
UserName string `json:"username"`
ImageURL string `json:"image_url"`
CountryCode string `json:"country_code"`
PhoneNumber string `json:"phone_number"`
}
and I want to have custom types and add regex check for these declared types! For ex for email I intend to have a custom type email which has regex check to verify if the data is proper email or not!
CodePudding user response:
You can validate your email using Go-validator lib
func validateVariable() {
myEmail := "joeybloggs.gmail.com"
errs := validate.Var(myEmail, "required,email")
if errs != nil {
fmt.Println(errs) // output: Key: "" Error:Field validation for "" failed on the "email" tag
return
}
}
or using its struct validator
func validateStruct() {
type User struct {
Email string `json:"email" validate:"email"`
}
u := &User{email: "[email protected]"}
err := validate.Struct(user)
//check err
}
CodePudding user response:
Yes, You can use regex
in golang
using regexp library
match, _ := regexp.MatchString("/^[^\s@] @[^\s@] \.[^\s@] $/", "[email protected]")