Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way use one data annotation/attribute with multiple properties?

Is it possible to use a single data annotation/attribute for multiple properties?

Instead of:

[Required]
public string Name {get;set;}
[Required]
public string Something {get; set;}
[Required]
public string Everything {get;set;}

One attribute for three properties:

[Required]
public string Name {get;set;}
public string Something {get; set;}
public string Everything {get;set;}

I know the second code block only sets Name to not null, but is there a way to make all three properties not null with only one [Required] attribute?

like image 859
BearSkyview Avatar asked Oct 28 '13 21:10

BearSkyview


2 Answers

There's no way to do specifically that.

If your goal is to minimize typing and add a single attribute that verifies all the members of a type are set, you can make a custom validation attribute and apply it to the type. It could use reflection to pull out all the properties of the type and check them.

like image 191
Cory Nelson Avatar answered Oct 06 '22 01:10

Cory Nelson


No there isn't.

Attributes need to be applied explicitly to each property.

I'm not sure what you want to save here. The coding effort is simply a copy and paste, and if the required fields ever changed you'd have to rearrange your code rather than just adding or removing the attribute from the modified properties.

How would the compiler know when to stop applying the [Required] attribute?

How would you arrange the code if there were multiple attributes, on different sets of properties?

like image 43
ChrisF Avatar answered Oct 06 '22 00:10

ChrisF