mikeerickson / validatorjs

A data validation library in JavaScript for the browser and Node.js, inspired by Laravel's Validator.
https://www.npmjs.com/package/validatorjs
MIT License
1.77k stars 280 forks source link

required_if doesn't work as expected #434

Open risanto opened 3 years ago

risanto commented 3 years ago

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,
min-emcloud commented 3 years ago
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`
hellohasan commented 2 years ago

@risanto did you find the solution?

AlessandroStaffolani commented 1 year ago

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`