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 does not work with nested objects #134

Closed davidspiess closed 7 years ago

davidspiess commented 7 years ago
const rules = {
  payment: {
    selection: 'required',
    method: 'required',
    invoice: 'boolean'
  },
  company: {
    name: 'required_if:payment.invoice,true',
    taxnumber: 'required_if:payment.invoice,true'
  }
};
garygreen commented 7 years ago

Other rules need to support nested objects, too:

orditeck commented 7 years ago

That's an important one 😕 I need this, gonna take a look if I have the chance this week.

orditeck commented 7 years ago

Replacing https://github.com/skaterdav85/validatorjs/blob/master/src/rules.js#L16

if (this.validator.input[req[0]] === req[1]) {

to

if (req[0].split('.').reduce(function index(obj,i) {return obj[i]}, this.validator.input) === req[1]) {

Seems to do the job just fine.

Someone could test & open a pull request? @skaterdav85 @garygreen

For now I just overwrite the required_if rule when needed (luckily I can do that for now!)

Validator.register('required_if', function(val, req, attribute) {
    req = req ? req.split(',') : [];
    if (req[0].split('.').reduce(function index(obj,i) {return obj[i]}, this.validator.input) === req[1]) {
        return this.validator.getRule('required').validate(val);
    }

    return true;
}, 'The :attribute field is required when :other is :value.');