Custom validation not working with async #1333
Answered
by
thetutlage
popovicieduard
asked this question in
Help
-
When using async with a custom validation rule, the rule passes and doens't invoke the errorReport.report() function, if I remove the async from the rule, everything works as intended, I would like to use the Database inside my rule so I can check for a unique constraint on a table based on some values. my rule: validator.rule('checkUniqueAccountEmail',async (value, _:any,{ field, arrayExpressionPointer,errorReporter,root,tip})=>{
/**
* Skip validation when value is not a string. The string
* schema rule will handle it
*/
if (typeof (value) !== 'string') {
return
}
if (!value) {
return
}
const accountId = validator.helpers.getFieldValue('accountId', root, tip) || null
console.log(accountId)
const userId = validator.helpers.getFieldValue('userId', root, tip)
console.log(userId)
const account = await Database
.from('accounts')
.where({emailAddress: value})
.where({userId})
.whereNot({uuid: accountId})
.first()
console.log(account)
if (account) {
console.log('aici')
errorReporter.report(field, 'checkUniqueAccountEmail', 'email_address is not unique', arrayExpressionPointer)
return
}
}) |
Beta Was this translation helpful? Give feedback.
Answered by
thetutlage
Jul 25, 2020
Replies: 1 comment 2 replies
-
You have to tell the validator in advance, that you are going to create an async validation by defining a third argument. async function validate () {}
async function compile () {
return {
async: true,
}
}
validator.rule('checkUniqueAccountEmail', validate, compile) Check the AdonisJS unique rule https://github.com/adonisjs/lucid/blob/develop/src/Bindings/Validator.ts#L188 |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
popovicieduard
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You have to tell the validator in advance, that you are going to create an async validation by defining a third argument.
Check the AdonisJS unique rule https://github.com/adonisjs/lucid/blob/develop/src/Bindings/Validator.ts#L188