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"