我不想禁用验证,但是向用户显示消息会很棒。虽然我认为用户不太可能在文本字段中包含&#,但我可以看到有人在自由文本字段中输入以<。
开头的内容。有没有办法检测是否会抛出验证异常,而是将其显示为验证消息?
答案 0 :(得分:0)
以下是解决此问题的方法:
创建验证规则,例如potentiallyDangerousRequestRule
:
var potentiallyDangerousRequestRegex = /[<>]|&#/, // <, >, &#
potentiallyDangerousRequestErrorMessage = 'The error message';
$.validator.addMethod('potentiallyDangerousRequestRule', function (value) {
if (value == '')
return true;
return !potentiallyDangerousRequestRegex.test(value);
}, potentiallyDangerousRequestErrorMessage);
$.validator.unobtrusive.adapters.addBool('potentiallyDangerousRequestRule');
在您要验证的validate
元素上调用form
方法:
$('form').validate({errorClass: 'input-validation-error'});
将规则添加到元素,例如所有文本输入和textareas:
$('input:text, textarea').each(function () {
$(this).rules('add', { potentiallyDangerousRequestRule: true });
});
确保在应用规则之前在表单上调用validate
方法。