Pass a parameter to a custom rule #3769
Answered
by
3adel-bassiony
3adel-bassiony
asked this question in
Help
-
How I can pass a request input or a variable to the rule? const orderSchema = schema.create({
user_id: schema.number([rules.exists({ table: 'users', column: 'id' })]),
address_id: schema.number([rules.exists({ table: 'addresses', column: 'id' })]),
products: schema.array([rules.minLength(1)]).members(
schema.object().members({
id: schema.number([rules.exists({ table: 'products', column: 'id' })]),
quantity: schema.number([rules.hasValidProductQuantity(id)]),
})
),
notes: schema.string.optional(),
}) how I can pass the product id to the rule validation of the quantity? |
Beta Was this translation helpful? Give feedback.
Answered by
3adel-bassiony
Jun 22, 2022
Replies: 1 comment
-
I posted this issue on Discord and I got this solution: validator.rule(
'hasValidProductQuantity',
async (value, _, options) => {
if (typeof value !== 'number') {
return
}
const id = validator.helpers.getFieldValue('id', options.root, options.tip)
const product = await Product.query().where('id', id).first()
if (!product) {
return
}
if (value > product!.quantity) {
options.errorReporter.report(
options.pointer,
'hasValidProductQuantity',
'hasValidProductQuantity validation failed',
options.arrayExpressionPointer
)
}
},
() => {
return {
async: true,
}
}
) So in this case I don't need to pass the product id to the rule |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
3adel-bassiony
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I posted this issue on Discord and I got this solution: