Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...