在此之后的帮助下,解决方案以最简单的形式在小提琴中起作用。但是在实施它时,它不起作用。所以我已经用之前给出的解决方案添加了实际代码。
我要做的是检查任何输入框和文本区域中的非法字符?摆弄实际代码就在这里。 Actual Code
$('.formsubfree').click(function () {
var str = $(this).prevAll("input, textarea").first().val();
if (/[%&<>\[\]{}]/.test(str) === true) {
alert('These characters & < > [ ] { } % are not allowed. Please remove them and try again.');
}
});
带有删除html的早期解决方案位于fiddle
由于
答案 0 :(得分:1)
我建议您使用当前的HTML格式:
$('.formsubfree').click(function () {
var invalid = ['%', '&', '<', '>', '[', ']', '{', '}'],
validate = $(this).prevAll(':input').first();
if (/[%&<>\[\]{}]/.test(validate.val())) {
console.log("Yeah, these characters ('" + invalid.join(', ') + "') aren't allowed. So stop it.");
}
});
或者可能:
$('.formsubfree').click(function (e) {
e.preventDefault(); // stop the submission of the form
var validate = $(this).prevAll(':input').first(),
found;
if (/[%&<>\[\]{}]/.test(validate.val())) {
found = validate.val().replace(/[^%&<>\[\]{}]/g,'').split('').join("', '");
console.log(found);
console.log("Yeah, these characters '" + found + "' aren't allowed. So stop it.");
}
else {
// if no errors were found, submit the form:
$('.formsubfree').closest('form').submit();
}
});
参考文献:
答案 1 :(得分:0)
您可以将验证方法与自定义规则一起使用,如下所示:
$.validator.addMethod("regex", function(value, element) {
return this.optional(element) || value === "NA"
|| value.match(/^[0-9,\+-@.A-Za-z ]+$/);
}, "Please enter a valid character");
它将丢弃除0-9,A-Z,a-z,@,+, - 和之外的所有字符。