Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

send params to govalidator custom messages #79

Open
aliworkshop opened this issue Sep 1, 2019 · 0 comments
Open

send params to govalidator custom messages #79

aliworkshop opened this issue Sep 1, 2019 · 0 comments

Comments

@aliworkshop
Copy link

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)
			}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant