Regular expression to limit string length

I have a problem when I need to use RegularExpressionValidator to limit the string length to 400 characters.

My expression was .{0,400}

My question is: is there a way to limit the length of characters to 400 without considering spaces?

I want to be able to accept spaces in a string, but not take it into length. Is it possible?

+7
regex
source share
2 answers

I really agree with Greg, but here you need a regular expression:

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

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

+11
source share

It looks like you can write your own validation class instead of using the RegularExpressionValidator. Regular expressions certainly have their uses, but that doesn't look like one of them.

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

+7
source share

All Articles