Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex length validation: Ignore leading and trailing whitespaces

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)?

like image 877
Espen S. Avatar asked Dec 11 '25 09:12

Espen S.


1 Answers

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.

like image 63
Marek Musielak Avatar answered Dec 13 '25 22:12

Marek Musielak