3

I have the following code block: -

using System.ComponentModel.DataAnnotations;
public class NewsItem
{            
        [RegularExpression(System.Configuration.ConfigurationSettings.AppSettings["UrlRegEx"], ErrorMessage = "Invalid link")]
        public string Url { get; set; }
}

This returns the error "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type".

How can I give the value in the first parameter of a RegularExpression attribute. I want to give the values from Web.Config variables. I am using this code in the Model class of EF.

Mansoor Gee
  • 1,071
  • 8
  • 20
  • What are the reasons you want to use web.config to store strings like this? Resources files, databases or declared constants are all pretty reasonable ways of doing this, but I've never heard of someone using a web.config appsettings for this. – Xhalent Oct 26 '11 at 11:18
  • @Xhalent Yes you are right. But I think getting value for RegularExpression from Web.Config appsettings is a quick way to change expression string whenever we need. Otherwise we have to compile the code. – Mansoor Gee Oct 26 '11 at 11:41

1 Answers1

0

You can point data annotation to pick the value from resource file

See ErrorMessageResourceName

OR

You can write your custom validation method and pick the value from there

See CustomValidationAttribute

OR

You can write a regular expression derived attribute class that can reads the value from web.config.

Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131