I am writing my own custom configuration section and have a ConfigurationProperty defined in a ConfigurationElement like so:
[ConfigurationProperty("startTime", IsRequired = false)]
[RegexStringValidator("\\d{2}:\\d{2}:\\d{2}")]
public string StartTime
{
get
{
return (string) this["startTime"];
}
set
{
this["startTime"] = value;
}
}
I am expecting to be able to enter values such as "23:30:00" in the startTime attribute of the ConfigurationElement that I have created. However, whenever I try to load my configuration section, I get an ConfigurationErrorsException with the message:
The value for the property 'startTime' is not valid. The error is: The value does not conform to the validation regex string '\d{2}:\d{2}:\d{2}'.
I'll admit I always struggle with regular expressions, but this one is simple enough and I wrote a test to verify that my pattern should validate the kinds of values I am expecting:
var regex = new Regex(@"\d{2}:\d{2}:\d{2}", RegexOptions.Compiled);
var isSuccess = regex.Match("23:30:00").Success;
isSuccess evaluates to True, so I am not quite sure why the ConfigurationErrorsException is being thrown.
As a reference, here is my configuration section from my App.config file:
<windowsServiceConfiguration>
<schedule startTime = "23:00:00" />
</windowsServiceConfiguration>
Any help as to why I can't get the RegexStringValidator to work would be appreciated. Thanks.
Try to define the default value that will pass the validation:
[ConfigurationProperty("startTime", IsRequired = false, DefaultValue = "00:00:00")]
[RegexStringValidator(@"\d{2}:\d{2}:\d{2}")]
public string StartTime
{
get
{
return (string) this["startTime"];
}
set
{
this["startTime"] = value;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With