Accessing request object inside register() registerAsync()
What version of this package are you using? 3.22.1
What problem do you want to solve? In some cases I need to access user model object (authenticated user) which is usually attach to request object and validate it against request payload. Maybe there are solutions for this needed but I can not find it so far in issues tab.
What do you think is the correct solution to this problem? I have some suggestions, but only basic concepts, as follows: My target is to add parameter field (req object) at these function: passes(), fails(), check(), checkAsync(), validate(), and _appy(), and modify the functions body as needed. The functions itself will be like these:
check: function (req)
checkAsync: function (passes, fails, req)
passes: function (passes, req)
fails: function (fails, req)
validate: function (inputValue, ruleValue, attribute, callback, req)
_apply: function (inputValue, ruleValue, attribute, callback, req)
And I can use them as follows:
Validator.register('same_branchcode', function(value, requirement, attribute, req) {
if (!req) {
throw new Error('Invalid Request Object')
}
return value === req.user.branchcode;
}, 'You can not view other branches account');
// And for validation inside controller:
const gagal = () => { throw new Error(validation.errors.all()) }
const passes = () => {};
const fails = () => {};
const validator = new Validator(data, rules)
await validator.checkAsync(passes, fails, req)
// OR for sync
if (!validator.check()) gagal()
if (!validator.check(req)) gagal() // if need request object or maybe other object which need to be accessed in custom validation
// OR for sync
if (!validator.passes() gagal()
if (!validator.passes(() => {}, req)) gagal() // if need request object
// OR for sync
validator.fails()
validator.fails(gagal, req) // if need request object
Implementation maybe dirty but it works for me.
Are you willing to submit a pull request to implement this change? Yes, but maybe not perfect.
This is really important, we can't write custom validators like similar to required_if