validatorjs
validatorjs copied to clipboard
Handle conditional validation
What version of this package are you using? 3.22.1
What problem do you want to solve?
I'll try explain case with under below code. I want to retrieve the "birthday" value only when the entityType is INDIVIDUAL. The current implementation works for this case, but I don't need the "birthday" parameter when the entityType is CORPORATE. To handle this, I created an ignore_if rule that ignores the "birthday" field if the entityType is CORPORATE.
const rules = {
entityType: "required|integer|in:" + `${Object.values(entityType).join(",")}`,
birthday: [
"date",
{ required_if: ["entityType", entityType.INDIVIDUAL] },
{ ignore_if: ["entityType", entityType.CORPORATE] },
],
};
What do you think is the correct solution to this problem?
The ignore_if rule can be a solution for this case. I solved this problem by adding the following code to the rules.js file.
ignore_if: function (val, req, attribute) {
req = this.getParameters();
if (this.validator._objectPath(this.validator.input, req[0]) === req[1]) {
delete this.validator.input[attribute];
}
},
Are you willing to submit a pull request to implement this change?
Yes, I can