javascript 如何验证文本框中的特殊字符并在错误消息中显示输入的特殊字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3554043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Validate special characters in a textbox and show entered special characters in the error message?
提问by naveen
There is a textbox and a button that validates the entry inside the textbox.
That if it should not validate the presence of illegal characters in the form.
Suppose I entered the following word "Lorem# %ipsum^"
有一个文本框和一个按钮,用于验证文本框内的条目。
那如果它不应该验证表单中非法字符的存在。
假设我输入了以下单词“Lorem# %ipsum^”
On clicking the button, two things should happen
单击按钮时,应该发生两件事
- If there sre any special chars like #$%^&, then the form submission should fail.
- An error message should pop up like "You have used the illegal characters #, % and ^ in your form"
- 如果有像#$%^& 这样的特殊字符,那么表单提交应该会失败。
- 应弹出一条错误消息,如“您在表单中使用了非法字符 #、% 和 ^”
What is the best method?
P.S: I would like a solution not involving jquery.
最好的方法是什么?
PS:我想要一个不涉及 jquery 的解决方案。
回答by Gumbo
You could do this:
你可以这样做:
var invalidChars = str.match(/[^\w ]/g), output = '';
if (invalidChars) {
invalidChars = invalidChars.unique();
var lastInvalidChar = invalidChars.pop();
output = 'You have used the illegal character' + (invalidChars.length > 0 ? 's' : '') + ' ' +
invalidChars.join(', ') + (invalidChars.length > 0 ? ' and ' : '') + lastInvalidChar;
}
Here matchand the regular expression /[^\w ]/gis used to get all characters that are neither word characters nor a space. The array of matched invalid characters is then cleaned from duplicates using the custom uniquemethod (see below). Then the last invalid character is removed from the array to append it if necessary with an “and” at the end of the output. The remaining invalid characters (if there are any) are then joined with commas and combined with the last invalid character.
这里match和正则表达式/[^\w ]/g用于获取既不是单词字符也不是空格的所有字符。然后使用自定义unique方法将匹配的无效字符数组从重复项中清除(见下文)。然后从数组中删除最后一个无效字符,并在必要时在输出末尾附加一个“和”。剩余的无效字符(如果有)然后用逗号连接并与最后一个无效字符组合。
Since JavaScript has no built-in uniquemethod to remove duplicates, you can use this method:
由于 JavaScript 没有unique删除重复项的内置方法,您可以使用此方法:
Array.prototype.unique = function() {
var index = {};
for (var i=0; i<this.length; ++i) {
if (!index.hasOwnProperty(this[i])) {
index[this[i]] = this[i];
}
}
var clean = [];
for (var prop in index) {
if (index.hasOwnProperty(prop)) {
clean.push(index[prop]);
}
}
return clean;
};
Note that this implementation is not type-safe as the values are used as property names and thus turned into strings. So ["3",3].unique()returns ["3"]hence "3".toString() === (3).toString().
请注意,此实现不是类型安全的,因为这些值用作属性名称并因此转换为字符串。所以["3",3].unique()返回["3"]因此"3".toString() === (3).toString()。
回答by Matyas
var myString = document.getElementById("myInputField").value; // gets the sentence
var invalidChars = myString.replace(/[^#%\^]*/g, ""); //gets the chars | "#%^" in your case
var response = "";
for(var i = 0; i < invalidChars.length; i+){
response += (i > 0? (i == invalidChars-1 ? " and ": ", "):"") + invalidChars[i];
}
if (response != "") {
alert("Your data contains invalid characters " + response);
}
For more info on js regexes check out
有关 js 正则表达式的更多信息,请查看

