Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataAnnotation with a configurable value?

Tags:

c#

asp.net-mvc

I'd like to set a DataAnnotation on a view model to a dynamic value that is configurable via the web.config. In the following example I get this error "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type". Anyone know if this is possible? Thanks

[DataType(DataType.Password)]
[RegularExpression(Properties.Settings.Default.PasswordExpression)]
public string Password { get; set; }
like image 494
NullReference Avatar asked Sep 15 '11 23:09

NullReference


People also ask

What is an attribute in data annotation?

We'll use the following Data Annotation attributes: Required – Indicates that the property is a required field. DisplayName – Defines the text to use on form fields and validation messages. StringLength – Defines a maximum length for a string field. Range – Gives a maximum and minimum value for a numeric field.

What is System ComponentModel DataAnnotations?

Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.

Which annotation can be used to set the name of a model that gets converted to a table thru code first approach?

Data Annotations - Table Attribute in EF 6 & EF Core. The Table attribute can be applied to a class to configure the corresponding table name in the database. It overrides the default convention in EF 6 and EF Core.


1 Answers

Attribute parameters must be constants, i.e. something whose value can be resolved at compile time. But you could write your own simple Attribute class that took the name of the the item in the appSettings, got the underlying value, and passed that on to the normal RegularExpression processing. Then your attribute would look like this:

[ConfigedRegularExpression("PasswordExpression")]

where PasswordExpression was the name of the app setting containing the actual regular expression string.

and, after writing this and doing a search (I should have done that first), I see someone's worked it out for you here:

How to write custom RegularExpressionValidator which takes the values from the config file?

like image 55
hatchet - done with SOverflow Avatar answered Oct 05 '22 01:10

hatchet - done with SOverflow