Resolving ConfigurationElements & Weird RegulardExpressionValidator Behaviour

I am currently architecting an inhouse .NET Class library Framework in our Web services team here at Ericsson. Part of the brief is to create custom Configuration sections within the application configuration files.

I was working on a custom ConfigurationElement for one of the configuration sections and I need a property that will hold an email address. The property is required and I needed to validate the value entered using a RegularExpressionValidator. Regular expressions are a great tool for easily verifying a string is in a certain format and Microsoft was nice enough to include the RegexStringValidatorAttribute. So I tried this:

<ConfigurationProperty("EmailAddress", IsRequired:=True), _
RegexStringValidator("^[a-zA-Z\.\-_]+@([a-zA-Z\.\-_]+\.)+[a-zA-Z]{2,4}$")>

If you know regular expressions then clearly a simple email address like my.boss@ericsson.com should validate. Well it did not work and  plus it gave me the misleading error that the email address wasn't validating.

After a bit of fiddling around, I figured out that at some point the RegexStringValidator is validating the default value. Since its value is required, it's never empty but I guess when it initializes it loads the default value (which is blank). Adding a DefaultValue that is valid did the trick.

<ConfigurationProperty("EmailAddress", IsRequired:=True, DefaultValue:="my.boss@ericsson.com"), _
RegexStringValidator("^[a-zA-Z\.\-_]+@([a-zA-Z\.\-_]+\.)+[a-zA-Z]{2,4}$")>

You don't have to worry about value of DefaultValue argument is a 'correct' address as long as it's valid, because if the value is not provided in the configuration file at all you'll get the error, "Required attribute 'EmailAddress' not found." and if you include an invalid email address, you'll get the error, "The value does not conform to the validation regex string"

Published Sunday, 01 Feb. 2009. 00:02

COMMENTS

 
Wed, 18 Mar. 2009. 09:03 by Terence Ndikum

Okay! I am sure anyone who has no idea what Regular Expressions are and what they are used for, would be like Sh***t! Looks like Algebra written in an Asiatic language. I need to revisit my old notes on Regular expressions to understand why the first one did not work; all the same its a good reminder of what the brain is capable of drafting for a machine to compute....we do everyday wihout even realising it...

Sun, 13 Dec. 2009. 15:12 by Faraz Shams

That DefaultValue surely did the trick. I have been scratching my head over this one for a while now. Almost gave up using RegexValidatorAttribute.

 

Leave a Comment

Your Name (required):
Your Comment (required):
67.19.2
Please enter the code above in the box below without the dots:
Other Great Blogs
Bimeyen's Blog
Ndikum's Blog
Check this great idea on how to Send Great gifts to family in Cameroon. Click below. Lost of people talking about it and using it too...

SEARCH

GO

ARCHIVES