ExpressJSでのバリデーション(express-validator)

フォームとか値の受け渡しに使うバリデーションですが、ExpressJSで簡単に使えそうなライブラリexpress-validatorがあったのでまとめておきます。

さっそくインストールから。

$ express -e validator
$ cd validator
$ npm install
$ npm install express-validator --save

/views/index.ejs

一般的なログインフォームです。

	<form action="/" method="post">
		<input type="text" name="name" id="name" value="" placeholder="name" /><br />
		<input type="password" name="password" id="passowrd" value="" placeholder="passowrd" /><br />
		<input type="submit" value="login" />
	</form>

/app.js

var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path')
  , expressValidator = require("express-validator");  //モジュールをロード

var app = express();

app.configure(function(){
  ...
  app.use(expressValidator);  //app.use(app.router);の前でないとエラーになります
  app.use(app.router);
  ...
});

app.get('/', routes.index);
app.post('/', routes.login);  //POSTのルーティングを設定

/routes/index.js

req.assert()でチェックし、req.validationErrors()でエラー内容を取得します。

exports.login = function(req, res){
	req.assert('name', 'Enter Name').notEmpty();
	req.assert('name', 'Enter Number').isInt();
	req.assert('password', 'Enter Password').notEmpty();

	var errors = req.validationErrors();
	console.log(errors);

	var mappedErrors = req.validationErrors(true);
	console.log(mappedErrors);

	res.render('index', {
		title: 'Express',
		errors: errors
	});
};

errorsは以下のような感じ。mappedErrorsは一つだけになってしまうようです。

[ { param: 'name', msg: 'Enter Name', value: '' },
  { param: 'name', msg: 'Enter Number', value: '' },
  { param: 'password', msg: 'Enter Password', value: '' } ]
{ name: { param: 'name', msg: 'Enter Number', value: '' },
  password: { param: 'password', msg: 'Enter Password', value: '' } }

チェックできるメソッドは上記の他、isAlpha()/isEmail()/len(6, 20)などがあるようです。

$ grep "function(" node_modules/express-validator/node_modules/validator/lib/validators.js | sort
    contains: function(str, elem) {
    equals: function(a, b) {
    isAfter: function(str, date) {
    isAlpha: function(str) {
    isAlphanumeric: function(str) {
    isArray: function(str) {
    isBefore: function(str, date) {
    isCreditCard: function(str) {
    isDate: function(str) {
    isDecimal: function(str) {
    isDivisibleBy: function(str, n) {
    isEmail: function(str) {
    isIP : function(str) {
    isIPNet: function(str) {
    isIPv4 : function(str) {
    isIPv6 : function(str) {
    isIn: function(str, options) {
    isInt: function(str) {
    isLowercase: function(str) {
    isNull: function(str) {
    isNumeric: function(str) {
    isUUID: function(str, version) {
    isUppercase: function(str) {
    isUrl: function(str) {
    len: function(str, min, max) {
    max: function(str, val) {
    min: function(str, val) {
    notContains: function(str, elem) {
    notEmpty: function(str) {
    notIn: function(str, options) {
    notNull: function(str) {
    notRegex: function(str, pattern, modifiers) {
    regex: function(str, pattern, modifiers) {

regex()で正規表現でのチェックもできますので、概ね問題なく使えそうです。