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?
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.
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?
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