Andrey
Andrey

Reputation: 21285

Regex to limit string length for strings with new line characters

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

Upvotes: 9

Views: 9840

Answers (3)

Yannick Motton
Yannick Motton

Reputation: 35971

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.

Upvotes: 13

Steve Wortham
Steve Wortham

Reputation: 22220

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.

Upvotes: 0

DA.
DA.

Reputation: 40673

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.

Upvotes: 0

Related Questions