开发者

Regex to limit string length for strings with new line characters

开发者 https://www.devze.com 2022-12-09 13:31 出处:网络
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!

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 lo开发者_StackOverflowok 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


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消