Validation for required attribute (as string)

Jul 7, 2010 at 9:55 AM

First a comment on the configuration section designer: great work! This simplified creating config sections a whole lot. The work I did in an entire day (mainly debugging) could now be done in a matter of one or two hours!

Unfortunately I've run into an issue that seems to be more a framework issue than a CSD issue:

When I configure an attribute to be a required string, with additional validation, a value is passed twice to my validator.

The first time it is the default value (which I explicitly did not enter on purpose), which is an empty string (not a null reference). Now my validator is an email address validator so this should return an exception, as an empty string is not a valid email address. The second time the actual configured value is passed to the validator, and this is valid (dependent on what I entered in the config file of course).

I see the generated code by CSD is correct by not specifying a default value to the ConfigurationPropertyAttribute

Also the the callbackvalidator seems to be properly bound: 

CallbackValidatorAttribute(Type:=GetType(EmailCallbackValidatorClass), CallbackMethodName:="ValidateCallback")

This class is partially generated by CSD, and passes the object to be validated to my custom method (without casting or converting the value).

So it seems all is properly done by CSD, and that the framework is a bit quirky.

I tried to do the following workaround:

I configured the default value to be a null-reference (nothing) (in CSD), and whenever a null-reference were to be passed to my validator, I'd accept it, as any entered value in the config file is bound to be at least an empty string. When the attribute would be omitted totally, the framework would detect the missing required attribute (I hoped). Unfortunately the default value was not passed as a null-reference but still as an empty string so the story ends.

I configured the default value as following:

ConfigurationPropertyAttribute(FromEmailPropertyName, IsRequired:=true, IsKey:=false, IsDefaultCollection:=false, DefaultValue:=Nothing)

Any ideas on how to validate a required string?