views:

787

answers:

3

Hi,

Looks like a simple task - get a regex that tests a string for particular length: ^.{1,500}$

But if a string has "\r\n" than the above match always fails!

How should the correct regex look like to accept new line characters as part of the string?

I have a <asp:TextBox TextMode="Multiline"> and use a RegularExpressionValidator to check the length of what user types in.

Thank you, Andrey

A: 

Can you strip the line breaks before checking the length of the string? That'd be easy to do when validating server-side. (In .net you could use a custom validator for that)

From a UX perspective, though, I'd implement a client-side 'character counter' as well. There's plenty to be found. jQuery has a few options. Then you can implement the custom validator to only run server-side, and then use the character counter as your client-side validation. Much nicer for the user to see how many characters they have left WHILE they are typing.

DA
I'm using asp.net's RegularExpressionValidator, it does both client and server side validation using provided regex
Andrey
My suggestion is to use the REGEX only server side (turn off client side for that control) as that's really just for validating data going into the DB. Client side, instead of validating it after the fact, I'd suggest a live 'character counter' as it's a much nicer indicator from the user experience perspective. This would really only make sense if you are already using jQuery or something as it'd be easy to add. If not, maybe not worth it just for this one field.
DA
er, let me rephrase...if the REGEX is still an issue, validate server-side using a custom control. You could just check for string length easily server-side and forget the REGEX. Then use the javascript method of live counting the characters client-side.
DA
+5  A: 

You could use the RegexOptions.Singleline option when validating input. This treats the input as a single line statement, and parses it as such.

Otherwise you could give the following expression a try:

^(.|\s){1,500}$

This should work in multiline inputs.

Yannick M.
Can you please replace closing bracket with curly bracket; otherwise it worked, thanks!
Andrey
Fixed the typo :-)
Yannick M.
A: 

The inability to set the RegexOptions is screwing you up here. Since this is in a RegularExpressionValidator, you could try setting the options in the regular expression itself.

I think this should work:

(?s)^.{1,500}$

The (?s) part turns on the Singleline option which will allow the dot to match every character including line feeds. For what it's worth, the article here also lists the other RegexOptions and the notation needed to set them as an inline statement.

Steve Wortham
+1 good suggestion. BTW, nice site (RegexHero.net) :)
Ahmad Mageed
Thanks man. I try. ;)
Steve Wortham
This expression breaks in client side validation - Javascript doesn't understand (?s)
Andrey
Ah yes, Javascript validation. Sorry about that.
Steve Wortham