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??
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):
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:
Notice that the use of
IsRequiredin both code examples, use the one that best fits your needs. Be aware that de default value is always going to be validated.