Skip to content

Handle conditional validation #473

Description

@FARUK-YILDIRIM

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

Activity

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