How can I create a custom rule of validator
I have added in start/hooks.js and look like the following:
const { hooks } = require("@adonisjs/ignitor")
hooks.before.httpServer(() => {
const Validator = use('Adonis/Addons/Validator')
Validator.extend('required_when_not', (data, field, message, args, get) => {
return new Promise((resolve, reject) => {
const fieldValue = get(data, args[0])
if(!fieldValue) {
return resolve('validation skipped')
}
if (fieldValue != args[1]) {
resolve('Allowed')
return
}
reject(message)
})
}, 'The field is required')
})
But seems is doesn't work
Can u please share what's not working or atleast what's the exception or error you are getting?
one issue I have spotted, it should be
fieldValue = get(data, field)
This rule is checked about the given field is required when the other field is not equal to given value. When I apply this rule in route validator, it's nothing show. Just a empty array returned
'use strict'
class StoreUser {
get rules () {
return {
field_a: 'required_when_not:field_b,ABC'
}
}
}
I have found what happen.
When extending the validator should use camelCase
e.g.
Validator.extend('requiredWhenNot', requiredWhenNotFn)
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.