LoginSignup
15
9

More than 5 years have passed since last update.

express-validatorを使った際のまとめ

Posted at

express-validatorを使って基本的なバリデーションのまとめ

環境

・node:8.10.0
・express-validator:5.3.0

epress-validator

npm

$ npm install --save express-validator

サンプルコード

app.js
// ...rest of the initial code omitted for simplicity.
const { check, validationResult } = require('express-validator/check');

app.post('/user', [
    check('name').isString(),
    check('name').isLength({ max: 30 }),
    check('password').isLength({ min: 7 })
], (req, res) => {
  // 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(422).json({ errors: errors.array() });
    }

    User.create({
        username: req.body.name,
        password: req.body.password
    }).then(user => res.json(user));
});

routeメソッド内でもOK

app.js
router.post('/user', [
    check('name').isString(),
    check('name').isLength({ max: 30 }),
    check('password').isLength({ min: 7 })
], (req, res) => {
// ~~~~~~~~~~~~~~
});
{
    "errors": [
        {
            "location": "body",
            "param": "name",
            "value": “foo&%$#*”,
            "msg": "Invalid value"
        },
        {
            "location": "body",
            "param": "password",
            "value": “Foo”,
            "msg": "Invalid value"
        }
    ]
}

オプション引数が長くなるのが嫌だったので別ファイルに移動

validator.js
import {check} from 'express-validator/check';

export const checkUser = [

    // こんな感じでバリデーションが設定できる
    check('name').isString(),
    check('name').isLength({ max: 30 }),
    check('email').isEmail(),
    check('email').isLength({ max: 255 }),
    check('password').isLength({ min: 7 , max: 128 }),
    check('password').isAlphanumeric()
];

カスタマイズする

既に登録済みの際はエラーを出したいとかありますよね、

validator.js
check('email').custom(email => {
    // 適当な処理
    if {
        // OK
    } else {
        return Promise.reject('');
    }
 }).withMessage('Error. Foo'),
{
    "errors": [
        {
            "location": "body",
            "param": "email",
            "value": “foo@foo.com”,
            "msg": “Error. Foo”
        }
    ]
}
15
9
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
15
9