Using the RegularExpressionValidator for validating length of text

Thursday, May 22nd, 2008 | .NET

The RegularExpressionValidator can be used for almost everything regarding validation of input fields. My favourites are validating Email, Dates and length of text in textareas. The only problem with the length validation, is validating text that includes newline. One would think that the regex: .{0,4000} would be an easy way to validate maximum length of 4000 characters. That is true, but the dot does not include NewLine (CheatSheet). The RegularExpressionValidator also does NOT have an option for parsing the text as single line, which is a common Regular Expression option.

Reading another blog I found an expression that includes newlines: ^(.|\s){0,n)$
The only problem with this is that IE 6/7 and FF freezes when trying to test the expression. Seems like this is a JavaScript/ECMAScript problem. Disabling the clientscript for the RegularExpressionValidator however would probably solve this. The expression works fine in RegexCoach.

A comment in the blog suggested in using:  ^[\s\S]{0,n}$
This expression seems to work fine in the browser. Also seems to work fine with number of characters. So I think I will stick with that for now.

Tags:

4 Comments to Using the RegularExpressionValidator for validating length of text

Nina Peddinti
February 6, 2009

The expression: ^[\s\S]{0,n}$ doesn't work for me. I can't seem to figure out why-my validation is for a text box which can accept a minimum of 6 characters and a max of 50.

^[\s\S]{6,50}$ No matter what I enter in the textbox, it generates the error msg…please help!

steve
October 16, 2009

Thanks so much !

zippy dippy
September 20, 2010

yer thing doesn't work, as mentioned above. maybe you'd like to recomment????

zacharydl
March 25, 2011

Just guessing here, but I think the "n" in ^[\s\S]{0,n}$ is supposed to be the maximum number of characters. Try ^[\s\S]{0,50}$ instead.

Leave a comment

Search

Knut Hamang

This is the official site for Knut Hamang. I am a professional technical consultant specialized in Microsoft and .NET technologies and platforms. I work as an independent consultant in Norway and have more than 10 years of professional experience. To get in contact with me, please send me an email or check my public profile on View Knut Hamang's profile on LinkedIn