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

Add AsRule Function to reuse struct validations as Rules #167

Open
glserranv opened this issue Feb 25, 2022 · 0 comments
Open

Add AsRule Function to reuse struct validations as Rules #167

glserranv opened this issue Feb 25, 2022 · 0 comments

Comments

@glserranv
Copy link

Is theres something like this? I basically need a way to convert a validation into a rule.

I wrote this which is useful to me but I would like this code to be in here rather than my source code.


func AsRule(v interface{}) Rule {
	return By(func(value interface{}) error {
		t := reflect.ValueOf(v)
		ptr := reflect.New(reflect.TypeOf(value))

		ptr.Elem().Set(reflect.ValueOf(value))

		in := []reflect.Value{ptr}
		out := t.Call(in)[0].Interface()
		if out != nil {
			return out.(error)
		}
		return nil
	})
}

I wrote basic unit test



type MyTestType struct {
	Foos []Foo
}

type Foo struct {
	IsValid bool
}

func ValidateFoo(f *Foo) error {
	return ValidateStruct(f,
		Field(&f.IsValid,
			Required,
		),
	)
}

func TestAsRule(t *testing.T) {

	failTest := MyTestType{
		Foos: []Foo{Foo{IsValid: false}},
	}

	err := ValidateStruct(&failTest,
		Field(&failTest.Foos,
			Each(AsRule(ValidateFoo)),
		),
	)

	if err == nil {
		t.Errorf("This has to error")
	}

	passTest := MyTestType{
		Foos: []Foo{Foo{IsValid: true}},
	}

	err = ValidateStruct(&passTest,
		Field(&passTest.Foos,
			Each(AsRule(ValidateFoo)),
		),
	)

	if err != nil {
		t.Errorf("%s", err.Error())
	}

}

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