I’ve defined a custom DataAnnotation attribute similar to this one that goes on the class but ensures that at least one property is populated. It works correctly and adds an error message to the model’s ValidationSummary. However, I want to be able to associate the error message with a particular property (or any string, really) so that I can display it in a particular place on my view.
Thus, if my custom attribute is used like this:
[RequireAtLeastOne(GroupId = 0, ErrorMessage = "You must specify at least one owner phone number.")]
public class UserViewModel: User {
...
}
then I want to be able to say something like:
[RequireAtLeastOne(GroupId = 0, ErrorMessage = "You must specify at least one owner phone number.", ValidationErrorKey = "my_key")]
public class UserViewModel: User {
...
}
…and use it in a view like this:
@Html.ValidationMessage("my_key")
It would also be fine if I had to associate the error message with a particular property on my model instead of an arbitrary string. How can I accomplish this?
You can implement IValidatableObject on your model and do the custom logic there, it will let you add the message using whichever key you want.