Reputation: 877
I'm trying to limit our users between 5 and 1024 characters per post.
We are currently using asp.net RegularExpressionValidator for this.
This is kinda working if I set the expression to the following:
body.ValidationExpression = string.Format("^[\\s\\S]{{{0},{1}}}$",
MinimumBodyLength,
MaximumBodyLength);
However, this does not take NewLines and leading/tailing/multiple spaces into account. So users can type stuff like: Ok (three spaces) . (dot), and it will still be validated because three spaces count as characters. The same goes for newlines. We can also type a single . (dot) followed by 5 spaces/newlines.
I have tried multiple regex variations I've found around the web, but none seem to fit my needs exactly. I want them to type minimum 5 characters, and maximum 3000 characters, but I don't really care how many newLines and spaces they use.
To clearify, I want people to be able to type:
Hi,
My name is ben
I do not want them to be able to type:
Hi .
or
A B
(lots of newlines or spaces)
It is possible that regex might not be the way to go? If so, how can I search and replace on the string before the regex evaluates (while still catch it in the validator with the old expression)?
Upvotes: 3
Views: 1207
Reputation: 27132
Use the regex below:
body.ValidationExpression = string.Format("^((\S)|((\s+|\n+|(\r\n)+)+\S)|(\S(\s+|\n+|(\r\n)+))+){{{0},{1}}}$",
MinimumBodyLength,
MaximumBodyLength);
It treats as single entity either a single character or single character after (or before) any number of whitespace characters.
Upvotes: 5
Reputation: 5757
If I understood you problem, you want to count only word characters. If that's the point, you could try this:
body.ValidationExpression = string.Format("^\w{{{0},{1}}}$",
MinimumBodyLength,
MaximumBodyLength);
Upvotes: 0