Skip to content

Instantly share code, notes, and snippets.

@youtalk
Created January 12, 2012 06:35
Show Gist options
  • Save youtalk/1599077 to your computer and use it in GitHub Desktop.
Save youtalk/1599077 to your computer and use it in GitHub Desktop.
Sanitizing and Japanese full/half-width character converting for Node.js
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