Reputation: 12660
I am building an MVC 5 app and have come to the point where I need to validate user input.
I would like to apply a [Required] attribute to a class that is not a built-in data type. Here is a snippet of my view model:
public class GraffitiViewModel : EformBase
{
[Required(ErrorMessage = "Please select yes or no")]
public RadioButtonList<YesNoType> GraffitiOffensive { get; set; }
[Required(ErrorMessage = "Please select yes or no")]
public RadioButtonList<YesNoType> GraffitiTag { get; set; }
// ... more stuff here
}
The RadioButtonList is a class that emits HTML markup for corresponding C# radio button definitions. The [Required] attribute is not working in this context. Is there a way I can extend either my RadioButtonList class, or the [Required] attribute, so I don't have to modify my ViewModel?
I am thinking along the lines of a custom attribute that will perform this validation or a method in my RadioButtonList that will return a bool indicating whether or not the validation succeeded.
Looking forward to your responses!
M
Upvotes: 2
Views: 14906
Reputation: 11957
The [Required]
attribute should fire if:
See MSDN for more details.
Alternatively you can use the code here to create a custom attribute which fires on whatever conditions you decide.
Upvotes: 1