Created
January 12, 2012 06:35
-
-
Save youtalk/1599077 to your computer and use it in GitHub Desktop.
Sanitizing and Japanese full/half-width character converting for Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var validator = require('validator'); | |
var hankaku = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ '; | |
var zenkaku = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ '; | |
var zenkakuToHankaku = function (word) { | |
for (var i = 0, n = zenkaku.length; i < n; i++) { | |
word = word.replace(new RegExp(zenkaku[i], 'gm'), hankaku[i]); | |
} | |
return word.replace(/^\s+|\s+$/g, ''); // trim head and tail white space | |
}; | |
var sanitize = function (param) { | |
return function (req, res, next) { | |
var map = req[param]; | |
if (map) { | |
for (var key in map) { | |
var word = map[key]; | |
if (typeof word === 'string') { | |
map[key] = validator.sanitize(zenkakuToHankaku(word)).xss(); | |
} | |
} | |
} | |
next(); | |
}; | |
}; | |
app.get('*', sanitize('query'), function (req, res, next) { | |
// do something | |
next(); | |
}); | |
app.post('*', sanitize('body'), function (req, res, next) { | |
// do something | |
next(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment