有没有更好的方法来使用javascript清理输入? [英] Is there a better way to sanitize input with javascript?
问题描述
我想编写一个javascript函数来清理用户输入并删除任何不需要的和危险的字符。
I wanted to write a javascript function to sanitize user input and remove any unwanted and dangerous characters.
它必须只允许以下字符:
It must allow only the following characters:
- Alfanumeric字符(不区分大小写):[az] [0-9]。
- 内部空格,如word1 word2。
- 西班牙文字符(案件不在意):[áéíóúñü]。
- 下划线和连字符[_-]。
- 点和逗号[。,]。
- 最后,必须使用trim()修剪字符串。
- Alfanumeric characters (case insentitive): [a-z][0-9].
- Inner whitespace, like "word1 word2".
- Spanish characters (case insentitive): [áéíóúñü].
- Underscore and hyphen [_-].
- Dot and comma [.,].
- Finally, the string must be trimmed with trim().
我的第一次尝试是:
function sanitizeString(str){
str = str.replace(/[^a-z0-9áéíóúñü_-\s\.,]/gim,"");
return str.trim();
}
但如果我这样做:
sanitizeString("word1\nword2")
它返回:
"word1
word2"
所以我不得不重写这个函数以去除发展中的真实情况\\\\\\\\\\\\\\\
$ b
So I had to rewrite the function to remove explícitly \t\n\f\r\v\0:
function sanitizeString(str){
str = str.replace(/([^a-z0-9áéíóúñü_-\s\.,]|[\t\n\f\r\v\0])/gim,"");
return str.trim();
}
我想知道:
- 有没有更好的方法来使用javascript清理输入?
- 为什么\ n和\t在第一次匹配时不匹配版本RegExp?
推荐答案
新版本的 sanitizeString 功能:
function sanitizeString(str){
str = str.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,"");
return str.trim();
}
@RobG和@Derek提到了主要问题:(@ RobG写道你的评论作为答案,我会接受它)\ n并不意味着现在 w3Schools说
The main problem was mentioned by @RobG and @Derek: (@RobG write your comment as an answer and I will accept it) \s doesn't mean what now w3Schools says
查找空白字符
Find a whitespace character
这意味着 MDN说
匹配单个空格字符,包括空格,制表符,表格
Feed,换行符。相当于[
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\ \\\ \\\ \\\ \\\ \\\ \\\ \\\ \\\ \ u205f \ u3000]。
Matches a single white space character, including space, tab, form feed, line feed. Equivalent to [ \f\n\r\t\v\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000].
我在编写函数时信任w3Schools。
I trusted in w3Schools when I wrote the function.
第二个更改是移动破折号字符( - )到最后为了避免它的范围分隔符含义。
A second change was to move the dash character (-) to the end in order to avoid it's range separator meaning.
- 注1:这是使用javascript的服务器端验证。
- 注2:
(适用于IBM Notes XPagers)我喜欢XPage SSJS中的javascript。对于我来说,这比Java方式更简单
。
这篇关于有没有更好的方法来使用javascript清理输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!