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; }
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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With