Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected RegexStringValidator failure in ConfigurationProperty in custom ConfigurationElement

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.

like image 304
Jed Avatar asked Nov 10 '10 21:11

Jed


1 Answers

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;
    }
}
like image 133
Andrei G Avatar answered Nov 06 '22 21:11

Andrei G