Model:
using System.ComponentModel.DataAnnotations;
using MySite.Validators;
namespace MySite.Models
{
public class AddItem
{
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
[TagValidation(ErrorMessage = "At least one tag is required")]
public virtual List<int> Tags { get; set; }
}
}
View:
@using (Html.BeginForm()) {
...
<div class="editor-label">
@Html.LabelFor(model => model.Tags, "Tags")
</div>
<div class="editor-field">
@Html.ListBox("Tags")
@Html.ValidationMessageFor(model => model.Tags)
</div>
...
}
Validator:
using System.ComponentModel.DataAnnotations;
namespace MySite.Validators
{
public class TagValidationAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
return false;
}
}
}
I want my validator to return false to begin with, just to make sure it’s working. However, if I don’t select any tags from the list and submit the form, it tries to process it without any errors indicating that I need to select a tag first.
What am I doing wrong here?
I had commented out the if (ModelState.IsValid == false) check in my controller, so I wasn’t getting any validation. The reason I did this, initially, was because I was getting an error when I tried to pass the model back to the view, because the ListBox field in the view expected a IEnumerable and not a List.
Here’s how I fixed both problems (in the controller):