Search code examples
javascriptnode.jsexpressexpress-validator

Express-validator: make field optional if other field value is true


I'm trying to make the Display Name of a user optional if the Anonymous checkbox is clicked.

For that, I'm using express-validator.

Check the following code out:

router
  .route("/create-checkout-session")
  .post(
    [     
      check("displayName") //if isAnonymous : true than this is optional
        .matches(vars.intlRegex)
        .trim()
        .escape()
        .withMessage("Please provide a display name")
        .optional({ checkFalsy: true }),
      check("isAnonymous").isBoolean()],//isAnonymous
    checkForErrors,
    createCheckoutSession

How can I validate in one field, the value of another field, and based on that make it optional.

Thanks in advance


Solution

  • You can use a if condition to handle that case. The condition is when isAnonymous is NOT true then execute another check for displayName

    router
      .route("/create-checkout-session")
      .post(
        [
          check("displayName")
            .if((value, { req }) => { // if isAnonymous : false then let's check
              return !req.body.isAnonymous;
            })
            .matches(vars.intlRegex)
            .trim()
            .escape()
            .withMessage("Please provide a display name")
          check("isAnonymous").isBoolean()
        ],
        checkForErrors,
        createCheckoutSession