问题
I have the following class:
public class CreateJob
{
[Required]
public int JobTypeId { get; set; }
public string RequestedBy { get; set; }
public JobTask[] TaskDescriptions { get; set; }
}
I'd like to have a data annotation above TaskDescriptions
so that the array must contain at least one element? Much like [Required]
. Is this possible?
回答1:
I've seen a custom validation attribute used for this before, like this:
(I've given sample with a list but could be adapted for array or you could use list)
public class MustHaveOneElementAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
var list = value as IList;
if (list != null)
{
return list.Count > 0;
}
return false;
}
}
[MustHaveOneElementAttribute (ErrorMessage = "At least a task is required")]
public List<Person> TaskDescriptions { get; private set; }
回答2:
It can be done using standard MinLengthAttribute validation attribute, but works ONLY for arrays:
public class CreateJob
{
[Required]
public int JobTypeId { get; set; }
public string RequestedBy { get; set; }
[MinLength(1)]
public JobTask[] TaskDescriptions { get; set; }
}
回答3:
Please allow me a side note on using MinLengthAttribute with .NET Core.
Microsoft recommends using Razor Pages starting with .NET Core 2.0.
Currently, The validation with MinLengthAttribute on a property within the PageModel does not work:
[BindProperty]
[Required]
[MinLength(1)]
public IEnumerable<int> SelectedStores { get; set; }
ModelState.IsValid returns true when SelectedStores.Count() == 0.
Tested with .NET Core 2.1 Preview 2.
回答4:
Here is a bit improved version of @dove solution which handles different types of collections such as HashSet, List etc...
public class MustHaveOneElementAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
var collection = value as IEnumerable;
if (collection != null && collection.GetEnumerator().MoveNext())
{
return true;
}
return false;
}
}
回答5:
MinLength attribute considers the value as valid if it's null. Therefore just initialize your property in the model as an empty array and it'll work.
MinLength(1, ErrorMessageResourceName = nameof(ValidationErrors.AtLeastOneSelected), ErrorMessageResourceType = typeof(ValidationErrors))]
int[] SelectedLanguages { get; set; } = new int[0];
来源:https://stackoverflow.com/questions/13361500/array-must-contain-1-element