LoginSignup
1
2

More than 3 years have passed since last update.

express-validatorの使い方メモ

Last updated at Posted at 2020-10-11

 はじめに

expressを使ってユーザー認証機能を作ったときに使ったexpress-validatorについて使い方をメモ

 使い方

router.ts
import express, { Request, Response } from 'express'; // TSなので型もインポート。一応。
import { body } from 'express-validator';

const router = express.Router();

router.post(
  '/api/users/signup',
  [
    body('email')  // req.body.emailがメールかどうかをvalidateしてくれる
      .isEmail()
      .withMessage('Email must be valid'),  // invaludであればメッセージを返す
    body('password')
      .trim()
      .isLength({ min: 4, max: 20 })  // req.body.passwordの文字数を指定
      .withMessage('Password must be between 4 and 20 characters')  // invaludであればメッセージを返す
  ],
  (req: Request, res: Response) => {  // 一応TSなので型を明記
    const { email, password } = req.body;

    if (!email || typeof email !== 'string') {
      res.status(400).send('Provide a valid email');
    }

    // new User({ email, password })
    // ここからユーザーを作成する
  }
);

export { router };

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2