express-validator ⇒ express基於validator

validator驗證內容

npm install -d express-validator

加入驗證

withMessage()

// routes/auth.js
const { check } = require("express-validator");

router.post(
  "/registered",
  check("email").isEmail().withMessage("自定義錯誤內容"),
  authController.postRegistered
);

("email") ⇒ 為input表單欄位

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/2b975ba1-b5b7-4450-b222-3739a15ea124/截圖_2021-08-11_下午4.34.06.png

加入validator

// controllers/auth.js
const { validationResult } = require("express-validator");

exports.postRegistered = (req.res.next) => {
	const errors = validationResult(req);

  if (!errors.isEmpty()) {

    return res.status(422).render("auth/registered", {
      docTitle: "會員註冊",
      breadcrumb: [
        { name: "首页", url: "/", hasBreadcrumbUrl: true },
        { name: "會員註冊", hasBreadcrumbUrl: false },
      ],
      errorMsg: errors.array()[0].msg,
    });
  }
}

加入自訂字串

// controllers/auth.js

router.post(
  "/registered",
  check("email")
    .isEmail()
    .withMessage("請輸入正確郵件")
    .custom((value, { req }) => {
      if (value === "[email protected]") {
        throw new Error("此郵件已註冊");
      }
			return true;
    }),
  authController.postRegistered
);

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/2fceeaf3-07a5-4a42-b76f-e5c68f616207/截圖_2021-08-11_下午5.22.44.png

加入更多驗證判斷

// routes/auth.js
router.post(
  "/registered",
  [
    check("email")
      .isEmail()
      .withMessage("請輸入正確郵件")
      .custom((value, { req }) => {
        if (value === "[email protected]") {
          throw new Error("此郵件已註冊");
        }
        return true;
      }),
    body("password")
      .isLength({ min: 5 })
      .withMessage("密碼需大於5位數")
      .isAlphanumeric()
      .withMessage("密碼須為英文或數字"),
  ],
  authController.postRegistered
);

也可以寫成

body("password", "密碼需大於5位數,且須為英文或數字")
	.isLength({ min: 5 })
	.isAlphanumeric()

非同步驗證處理

在路由層處理非同步(信箱)處理

// routes/auth.js
// 引入User
const User = require("../models/user");

router.post(
"/registered",
	[
		check("email")
		  .isEmail()
		  .withMessage("請輸入正確郵件")
		  .custom((value, { req }) => {
		    return User.findOne({ email: value }).then((userDoc) => {
		      if (userDoc) {
		        return Promise.reject("該用戶已經存在");
		      }
		    });
		  }),
	],
  authController.postRegistered
);