rules := govalidator.MapData{
"title": []string{"required"},
"description": []string{"required", "min:4", "max:20"},
"file:image": []string{ "mime:image/jpg,image/png"},
"file:file": []string{ "mime:video/mp4","size:1000"},
}
messages := govalidator.MapData{
"title": []string{"required: Is Required"},
"description": []string{"required: Is Required","max: must be %d chars maximum"},
"file:image": []string{"required: Is Required"},
"file:file": []string{"required: Is Required"},
}
opts := govalidator.Options{
Request: r, // request object
Rules: rules, // rules map
Messages: messages, // custom message map (Optional)
RequiredDefault: true, // all the field to be pass the rules
}
vgov := govalidator.New(opts)
return vgov.Validate()
if we want send params to custom messages we have to write params statically
but if you change rules.go file like this , we can send any params to custom messages
i change max rule for example
AddCustomRule("max", func(field string, rule string, message string, value interface{}) error {
mustLen := strings.TrimPrefix(rule, "max:")
lenInt, err := strconv.Atoi(mustLen)
if err != nil {
panic(errStringToInt)
}
lenFloat, err := strconv.ParseFloat(mustLen, 64)
if err != nil {
panic(errStringToFloat)
}
errMsg := fmt.Errorf("The %s field value can not be greater than %d", field, lenInt)
if message != "" {
errMsg = fmt.Errorf(message, lenInt)
}
errMsgFloat := fmt.Errorf("The %s field value can not be greater than %f", field, lenFloat)
if message != "" {
errMsgFloat = fmt.Errorf(message, lenFloat)
}
rv := reflect.ValueOf(value)
switch rv.Kind() {
case reflect.String:
inLen := rv.Len()
if inLen > lenInt {
if message != "" {
return fmt.Errorf(message, lenInt)
}
return fmt.Errorf("The %s field must be maximum %d char", field, lenInt)
}
...
if we want send params to custom messages we have to write params statically but if you change rules.go file like this , we can send any params to custom messages
i change max rule for example