memvalidasi objek bersarang menggunakan validator ekspres

Terkadang Anda perlu memvalidasi objek. Jika objek diperlukan, itu sederhana:

req.body = {
    user: {
        email: "email@test.com",
        password: "pass"
    }
}

validator seperti:

app.post(
  '/user',
  // user is a required object
    body('user').exists().isObject(),
  // email must be an email
    body('user.email').exists().isEmail(),
  // password must be at least 5 chars long
    body('user.password').exists().isLength({ min: 3 }),

  (req, res, next) => {
    // Finds the validation errors in this request and wraps them in an object with handy functions
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    next()
  },
);

Apa yang terjadi jika objek pengguna bersifat opsional, tetapi jika email dan kata sandi yang ada diperlukan?

app.post(
  '/user',
  // user is a required object
    body('user').exists().isObject(),
  // email must be an email
    body('user.email')
        .if(body('user').exists()) // check if user property exists
        .exists() // then check user.email to exists
        .isEmail(),
  // password must be at least 5 chars long
    body('user.password')
        .if(body('user').exists())
        .exists().isLength({ min: 3 }),

  (req, res, next) => {
    // Finds the validation errors in this request and wraps them in an object with handy functions
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    next()
  },
);