validatorjs
validatorjs copied to clipboard
required_with and required_if rules cannot handle 0 value
Sample code :
method: 'numeric', description: 'required_with:method|required_if:method,0'
Validations are not triggered when method value is 0.
@regalskr2006 Please were you able to resolve this?
@smithaitufe I am reviewing issues as I prepare v4
Would you please provide some sample code which demonstrates this issue not working
@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
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');
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