validatorjs icon indicating copy to clipboard operation
validatorjs copied to clipboard

required_if doesn't work as expected

Open risanto opened this issue 4 years ago • 3 comments

So, I set up these rules:

channel: 'required|numeric',
url: 'required_if:channel,1|url_validation',

And it's supposed to check for url when the channel is 1, but the problem is when I send this payload it passes just fine and doesn't trigger required or the subsequent url_validation (a custom validation).

"channel": 1,
"url": null,

risanto avatar Aug 06 '21 03:08 risanto

const Validator = require('validatorjs')

const data = {
  name: 'John',
  hasAllergy: true
};

const rules = {
  name: 'required',
  hasAllergy:  'required|boolean',
  allergicTo: 'required_if:hasAllergy,true'
}

const validation = new Validator(data, rules)
console.log('validation result', validation.passes()) // expected `false` but shows `true`

min-emcloud avatar Oct 05 '21 00:10 min-emcloud

@risanto did you find the solution?

hellohasan avatar Jan 08 '22 09:01 hellohasan

As shown in this closed issue #252. You can solve it using the array/object notation. Here is a working example:

const Validator = require('validatorjs');

const data = {
  name: 'John',
  hasAllergy: true,
};

const rules = {
  name: ['required'],
  hasAllergy: ['required', 'boolean'],
  allergicTo: [{ required_if: ['hasAllergy', true] }],
};

const validation = new Validator(data, rules);
console.log('validation result', validation.passes()); // expected `false` and shows `false`

AlessandroStaffolani avatar Feb 05 '23 18:02 AlessandroStaffolani