Last active
August 17, 2019 17:00
-
-
Save dumindu/6acf469069e1b4e1504cc55b11cbcb46 to your computer and use it in GitHub Desktop.
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
import "regexp" | |
const ( | |
alphaSpaceRegexString string = "^[a-zA-Z ]+$" | |
dateRegexString string = "^(((19|20)([2468][048]|[13579][26]|0[48])|2000)[/-]02[/-]29|((19|20)[0-9]{2}[/-](0[469]|11)[/-](0[1-9]|[12][0-9]|30)|(19|20)[0-9]{2}[/-](0[13578]|1[02])[/-](0[1-9]|[12][0-9]|3[01])|(19|20)[0-9]{2}[/-]02[/-](0[1-9]|1[0-9]|2[0-8])))$" | |
) | |
func New() *validator.Validate { | |
// ... | |
validate.RegisterValidation("alpha_space", isAlphaSpace) | |
validate.RegisterValidation("date", isDate) | |
return validate | |
} | |
func isAlphaSpace(fl validator.FieldLevel) bool { | |
reg := regexp.MustCompile(alphaSpaceRegexString) | |
return reg.MatchString(fl.Field().String()) | |
} | |
func isDate(fl validator.FieldLevel) bool { | |
reg := regexp.MustCompile(dateRegexString) | |
return reg.MatchString(fl.Field().String()) | |
} | |
func ToErrResponse(err error) *ErrResponse { | |
// ... | |
for i, err := range fieldErrors { | |
switch err.Tag() { | |
// ... | |
case "alpha_space": | |
resp.Errors[i] = fmt.Sprintf("%s can only contain alphabetic and space characters", err.Field()) | |
case "date": | |
resp.Errors[i] = fmt.Sprintf("%s must be a valid date", err.Field()) | |
// ... | |
} | |
} | |
//... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment