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

May I add custom my validator rule ? #71

Closed
aloha1003 opened this issue Jul 2, 2018 · 1 comment
Closed

May I add custom my validator rule ? #71

aloha1003 opened this issue Jul 2, 2018 · 1 comment

Comments

@aloha1003
Copy link

I want to add some custom validator rule base on your validator
How can I do to add custom rule ?

@renatosuero
Copy link

Hi @aloha1003 , in the readme there is a example how to use custom validators.

Custom validators

It is possible to define custom validators by using SetValidationFunc. First, one needs to create a validation function.

// Very simple validator
func notZZ(v interface{}, param string) error {
	st := reflect.ValueOf(v)
	if st.Kind() != reflect.String {
		return errors.New("notZZ only validates strings")
	}
	if st.String() == "ZZ" {
		return errors.New("value cannot be ZZ")
	}
	return nil
}

Then one needs to add it to the list of validators and give it a "tag" name.

validator.SetValidationFunc("notzz", notZZ)

Then it is possible to use the notzz validation tag. This will print "Field A error: value cannot be ZZ"

type T struct {
	A string  `validate:"nonzero,notzz"`
}
t := T{"ZZ"}
if errs := validator.Validate(t); errs != nil {
	fmt.Printf("Field A error: %s\n", errs["A"][0])
}

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

3 participants