core icon indicating copy to clipboard operation
core copied to clipboard

How can I create a custom rule of validator

Open silencechow opened this issue 9 years ago • 4 comments

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

silencechow avatar Nov 08 '17 06:11 silencechow

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)

thetutlage avatar Nov 08 '17 06:11 thetutlage

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'
            }
        }
}

silencechow avatar Nov 08 '17 06:11 silencechow

I have found what happen. When extending the validator should use camelCase e.g. Validator.extend('requiredWhenNot', requiredWhenNotFn)

silencechow avatar Nov 09 '17 03:11 silencechow

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.

lock[bot] avatar Mar 11 '20 11:03 lock[bot]