作者姓名: Yuan Huang

網頁

使用 express-validator

// router

const adminValidator = require('../validators/admin.validator');

...

router.post(
  '/shop-type/create',
  adminValidator.checkShopTypeFormData(),
  shopTypeController.createShopType
);
// admin.validator.js

const { body } = require('express-validator');

function checkShopTypeFormData() {
  return [body('name').trim().notEmpty().withMessage('請輸入商店類別')];
}

function checkShopFormData() {
  return [
    body('name').trim().notEmpty().withMessage('請輸入商店'),
    body('phone').trim().notEmpty().withMessage('請輸入電話'),
    body('note').optional().trim(),
    body('type').isNumeric().withMessage('請選擇類別'),
  ];
}

module.exports = { checkShopTypeFormData, checkShopFormData };
// controller

const { matchedData, validationResult } = require('express-validator');

...

const result = validationResult(req);

if (!result.isEmpty()) {
  ShopType.findAll()
    .then((shopTypeList) => {
      res.render('admin/shop/createShopForm', {
        errors: result.array(),
        old: req.body,
        shopTypeList,
      });
    })
    .catch((err) => {
      console.log(err);
    });
} else {
  const formData = matchedData(req);

  ShopType.findByPk(formData.type)
    .then((data) => {
      if (data === null) {
        res.send('404 Not Found');
        return;
      }

      return Shop.create({
        name: formData.name,
        phone: formData.phone,
        note: formData.note,
        shopTypeId: formData.type,
      });
    })
    .then((data) => {
      if (data) {
        res.redirect('/admin/shops');
      }
    })
    .catch((err) => {
      console.log(err);
    });
}
// view

<% if (errors.length > 0) { %>
<div>
  <% errors.forEach((err) => { %>
  <p><%= err.msg %></p>
  <% }) %>
</div>
<% } %>
系統

[MySQL] 把 JOIN 後的結果新增到資料表

INSERT INTO my_results
SELECT
  `unsubscribe`.`email`,
  `customer`.`id`,
  `customer`.`reg_datetime`,
  `customer`.`name`,
  `customer`.`sex`,
  `customer`.`birthday`,
  `customer`.`user_mailok`
FROM `unsubscribe`
LEFT JOIN `customer`
ON `unsubscribe`.`email` = `customer`.`email`;

資料表 my_results 要在跑上面的 SQL 語法前先設定好。


參考連結:

返回頂端