Skip to content

required_if doesn't work as expected #434

Open

Description

@risanto

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,

Activity

  1. min-emcloud commented on Oct 5, 2021

    @min-emcloud
    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`
    
  2. hellohasan commented on Jan 8, 2022

    @hellohasan

    @risanto did you find the solution?

  3. AlessandroStaffolani commented on Feb 5, 2023

    @AlessandroStaffolani

    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`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions