tgriesser / checkit

simple, flexible validations for node and the browser
MIT License
223 stars 53 forks source link

Pass context to conditional function in "maybe" clause #77

Closed sboehler closed 7 years ago

sboehler commented 7 years ago

Use case: Implementing a "get" method which fetches an object by certain parameters.

I am passing the user in the context object to the rules.run method. However, currently the context can't be evaluated in the conditional function of the 'maybe' clause.

This small pull request enhances the signature of the conditional function and allows the above use case to be implemented as:

const rules = new Checkit({
    id: ['integer'],
    user_id: ['integer', (val, context) => context.user.admin || context.user.id === val],
    name: ['string']
})
.maybe({ user_id: 'required' }, (id, context) => !context.user.admin);

Then, validation is run using

paramRules.run(params, { user })
.then(...)

Let me know what you think, I appreciate any feedback!

rhys-vdw commented 7 years ago

Yep. This makes sense. Could you add a test and include some documentation in the README please?

sboehler commented 7 years ago

Thanks @rhys-vdw for the quick reply. I have updated my branch with a test (both run and runSync) and updated the README. Let me know if you need anything more.

rhys-vdw commented 7 years ago

Thanks @sboehler. Looks good!