2

I don't want to disable validation, however it would be great to display a message to a user. Whilst I think it is highly unlikely that a user will ever have a legitimate need to include &# in a text field, I can see someone typing in a free text field something starting with a <.

Is there a way to detect that a validation exception would be thrown and instead display it as a validation message?

Sam
  • 946
  • 7
  • 19
  • You could use `[ValidateInput(false)]` on your action and then html encode the input in your controller OR view using `HttpUtility.HtmlEncode()`. This way you don't have to worry about validating input. – Oliver Aug 30 '13 at 07:45
  • @Oliver Thanks, but this is not practical. We have a very large application with many screens and I do not want to do this for each individual method. – Sam Aug 30 '13 at 07:47
  • Ok, in that case there are some good suggestions here: http://stackoverflow.com/questions/204646/how-to-validate-that-a-string-doesnt-contain-html-using-c-sharp – Oliver Aug 30 '13 at 07:51

1 Answers1

0

Here is the way I resolved this issue:

  1. Create a validation rule, say 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. Call validate method on the form element you want to validate:

    $('form').validate({errorClass: 'input-validation-error'});
    
  3. Add the rule to elements, for instance all text inputs and textareas:

    $('input:text, textarea').each(function () {
        $(this).rules('add', { potentiallyDangerousRequestRule: true });
    });
    

Make sure you call validate method on the form before applying the rule.

Zabavsky
  • 13,340
  • 8
  • 54
  • 79