Wednesday, April 6, 2011

Validating multi-line text input when using .NET

I have an HtmlTextArea and I want to restrict the number of characters users can input to 500.

Currently I've used a RegularExpressionValidator...

RegularExpressiondValidator val = new RegularExpressiondValidator ();
val.ValidationExpression = "^.{0,500}$";
val.ControlToValidate = id;
val.ErrorMessage = "blah";

... this is fine when the text is entered on a single line but it instantly fails validation whenever the text includes a new line character (ie. is multi-line).

I realise there are different regular expression engines and I need to test with the .NET one (can anyone point me in the direction of a good one online?) but I've tried a couple of other things including prepending "(?m)" to my expression string, and replacing ^ and $ with \A and \Z but so far no luck.

A further related question, can I avoid using a regular expression at all and link this validator to my own validation function somehow?

From stackoverflow
  • the "." does not include new lines.

    ^((.|\n){0,500})$

    This page might also help, its a regex cheat sheet.

    JaredPar : You need to use parens instead of brackets. Brackets indicate Or but you added the | in their as well.
    ccook : Yea, i immediately updated it after I realized I had done that.
    JaredPar : I thought about it some more and I believe it would still have worked. The | in that case was just superfluous. I can't 100% remember though if \n in a [] is treated as 2 characters or a newline escape.
    ccook : I don't think it would work... at least it hasn't for me in php and .net. You were right :)
  • Change your regex to the following

    "^(.|\n){0,500}$";
    

    The . character matches everything except a newline. The or clause will fix your problem.

  • I would do this in two ways, if you know javascript and want to restrict the client side character length you could do it with jQuery (a popular javascript extension library).

    $(document).ready(function(){
      var $TextBox = $("#<%=TextBox.ClientID %>");
    
      $TextBox.keyup(function(){
         return $TextBox.length <= <%=TextBox.MaxLength %>;
      });
    });
    

    Then do a similar check server-side with a Custom Validator or in your button click method.

    There are also ways to enable and disable ASP.Net Validators with javascript so you could look into that as well.

    ccook : Interesting, but don't you lose the 'completeness' of the control? That is, half of the validation is in the server side validator, while the other half is in the page?
    hunter : you're solution is obviously the most elegant. I just thought I would throw out an alternative. I have ASP.Net Validators for some things.

0 comments:

Post a Comment