Maninder
Maninder

Reputation: 1261

Validation in Custom web config section class

I have a custom web config class. I want to add RegexStringValidator as an attribute to a web config property like:

[ConfigurationProperty("siteDomainName", DefaultValue = "")]
        [RegexStringValidator(@"^([a-zA-Z0-9_-]*(?:\.[a-zA-Z0-9_-]*)+):?([0-9]+)?/?")]
        public string SiteDomainName
        {
            get
            {
                return (string) this["siteDomainName"];
            }
            set 
            { 
                this["siteDomainName"] = value;
            }
        }

The error i am getting is :

The value does not conform to the validation regex string '^([a-zA-Z0-9_-]*(?:.[a-zA-Z0-9_-]*)+):?([0-9]+)?/?'.

Even if the value supplied is correct and matches the Regex. What is the problem with this??

Upvotes: 0

Views: 1314

Answers (1)

Michiel van Oosterhout
Michiel van Oosterhout

Reputation: 23084

Like ronen said in his comment, your default value should also match the regular expression. See this answer for example: https://stackoverflow.com/a/5313223/4830. The reason is that the default value is also evaluated and validated, even when you set a value in your web.config file.

Something like this should work (default value validates, and property is required so it should never actually use the default value in practice):

[ConfigurationProperty("siteDomainName", DefaultValue="www.example.com", IsRequired=True)]
[RegexStringValidator(@"^([a-zA-Z0-9_-]*(?:\.[a-zA-Z0-9_-]*)+):?([0-9]+)?/?")]
public string SiteDomainName
...

In case you don't want a default value, you could change the regular expression to accept the empty string, by making the whole value basically optional:

[ConfigurationProperty("siteDomainName", IsRequired=False)]
[RegexStringValidator(@"^(([a-zA-Z0-9_-]*(?:\.[a-zA-Z0-9_-]*)+):?([0-9]+)?/?)?$")]
public string SiteDomainName
...

Notice that the use of IsRequired in both code examples, use the one that best fits your needs. Be aware that de default value is always going to be validated.

Upvotes: 1

Related Questions