validatorjs icon indicating copy to clipboard operation
validatorjs copied to clipboard

required_with and required_if rules cannot handle 0 value

Open ghost opened this issue 6 years ago • 5 comments

Sample code : method: 'numeric', description: 'required_with:method|required_if:method,0'

Validations are not triggered when method value is 0.

ghost avatar Mar 19 '19 04:03 ghost

@regalskr2006 Please were you able to resolve this?

smithaitufe avatar Jun 13 '19 12:06 smithaitufe

@smithaitufe I am reviewing issues as I prepare v4

Would you please provide some sample code which demonstrates this issue not working

mikeerickson avatar Nov 27 '19 19:11 mikeerickson

@mikeerickson

Not exactly the same issue, but it goes to show that the required_with function does not work as expected. Sample code:

const valueMap = {
  "function": null,
  "first_name": null,
  "last_name": null,
  "country": null,
  "email": null,
  "telephone": "123456",
  "mobile": null
}

const validation = {
  "country": [
    "required_with:telephone,mobile"
  ]
}

const validator = new Validator(valueMap, validation);
const passesValidation = validator.passes(); // returns true

I'm expecting the validator not to pass ('country' is a required field when either of 'telephone' or 'mobile' is filled), but it passes anyway...

I'm on 3.18.1

pepijnolivier avatar Dec 12 '19 14:12 pepijnolivier

Hi.

The issue comes from the fact that required_if rule takes it's parameter as string, so what it's doing is: 0 === '0'.

As a workaround, I used the registerImplicit method provided by Validator class:

const required_if_rule = function (val, req, attribute) {
        req = this.getParameters();
        let op = this.validator._objectPath(this.validator.input, req[0]);        
        if ((op != undefined && op != null ? op.toString() : null) === req[1]) {
            return this.validator.getRule('required').validate(val);
        }
        return true;
    }

Validator.registerImplicit('required_if', required_if_rule, 'The :attribute field is required when :other is :value');

codebury avatar Dec 31 '19 05:12 codebury

I can see the point here. Let me stew on this for a bit. My initial thinking is, if the value is required, but an empty string is supplied, theoretically that should fail validation.

Now, on the bad side, if I make this change, then I risk breaking other applications which don’t adopt this strictness

mikeerickson avatar Jan 01 '20 02:01 mikeerickson