var spclChrs="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
/*Accepted Characters*/
var id = $(this).attr('id');
var textVal = $("#" + id).val();
$("#" + id).css({ "background": "", "border": "" });
for (var i = 0; i < textVal.length; i++) {
if (spclChrs.indexOf(textVal.charAt(i)) == -1) {
if (sessionLang == 0) {
$().toastmessage('showErrorToast', "Invalid character(s) entered.");
}
if (sessionLang == 1) {
$().toastmessage('showErrorToast', "Los caractere(s) entraron.");
}
$("#" + id).css({ "background": "#FFCECE", "border": "1px solid red", });
textVal = textVal.slice(0, -1);
$("#" + id).val(textVal);
return false;
}
}
我对keyup和keydown事件的文本框进行了以下验证。我接受我的变量&#34; spclChars&#34;中指定的字符。而不是手动指定字符,我如何通过Ragex保持我的代码相同。
答案 0 :(得分:0)
我想说以下是你的目标:
// Regular expression to check against
// [^ creates a negative character class, saying that it only looks for characters NOT defined in this class
// \w = Any (english) alphanumerical characters (a-zA-Z0-9)
// -_
// ] end of class
// This [^\w-_] means any character that isn't a-zA-Z0-9-_.
// g = global flag
var reg = /[^\w-_]/g;
var id = $(this).attr('id');
var textVal = $("#" + id).val();
$("#" + id).css({ "background": "", "border": "" });
// Test the string towards the regular expression
// true = fits the expression (Have used special characters)
// false = Doesn't fit (only used a-zA-Z0-9-_)
if (reg.test(textVal)) {
if (sessionLang == 0) {
$().toastmessage('showErrorToast', "Invalid character(s) entered.");
}
if (sessionLang == 1) {
$().toastmessage('showErrorToast', "Los caractere(s) entraron.");
}
$("#" + id).css({ "background": "#FFCECE", "border": "1px solid red", });
textVal = textVal.slice(0, -1);
$("#" + id).val(textVal);
return false;
PS:你的例子最后似乎缺少一些代码:)