tags:

views:

430

answers:

2

I have an issue where I need to use a RegularExpressionValidator to limit the length of a string to 400 Characters.

My expression was .{0,400}

My question: Is there a way to limit the length of characters to 400 without taking into consideration blank spaces?

I want to be able to accept blank spaces in the string but not count it in the length. Is this possible?

+5  A: 

It sounds like you might want to write your own validator class instead of using the RegularExpressionValidator. Regular expressions certainly have their uses, but this doesn't sound like one of them.

Your custom validator could remove all the spaces, then check the length of the string. Ultimately, the code will be more readable than a regular expression that does the same thing.

Greg Hewgill
I agree, just remove all whitespace and check the string's length. Probably very efficient compared to the regex suggested above (although this is just a theory).
Joseph Pecoraro
+7  A: 

I pretty much agree with Greg, but here's the regex you want:

^\s*([^\s]\s*){0,400}$

@Boopid: If you really meant only the space character, replace \s with a space in the regex.

RichieHindle
Shouldn't that be [^\s] instead of [^ ]? Other than that: nice!
Stephan202
(or does the questioner by 'blank spaces' really only mean the space character?)
Stephan202
Or simply \S instead of [^\s]
Peter Boughton
@Stephan202: Quite right - edited. Thanks!
RichieHindle
@Peter, ah yes, that is obviously nicer.
Stephan202
And if only regular spaces are to be checked for then "^ ([^ ] ){0,400}$" is the expression (without quotes)
Peter Boughton
@Peter: You need some asterisks in there, or it will only match space-character-space-character-space-character-space...
RichieHindle
RicheiHindle - ooops, yes there should be a pair of asterisks there. Not sure how I missed those. :$
Peter Boughton
I agree that Greg's solution would be the best, but this helped in my case. Thank you!
GBriones