将失败的请求验证冒泡到MVC中的控制器

时间:2013-08-30 07:34:22

标签: asp.net asp.net-mvc

我不想禁用验证,但是向用户显示消息会很棒。虽然我认为用户不太可能在文本字段中包含&#,但我可以看到有人在自由文本字段中输入以<。

开头的内容。

有没有办法检测是否会抛出验证异常,而是将其显示为验证消息?

1 个答案:

答案 0 :(得分:0)

以下是解决此问题的方法:

  1. 创建验证规则,例如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');
    
  2. 在您要验证的validate元素上调用form方法:

    $('form').validate({errorClass: 'input-validation-error'});
    
  3. 将规则添加到元素,例如所有文本输入和textareas:

    $('input:text, textarea').each(function () {
        $(this).rules('add', { potentiallyDangerousRequestRule: true });
    });
    
  4. 确保在应用规则之前在表单上调用validate方法。