Reputation: 874
I have a model with property
[Display(Name = "Phone")]
public List<Phone> PhoneNumbers { get; set; }
I want to validate that List should be greater then 0
Suggest me the code.
/// <summary>
/// Atleast one phone number is required
/// </summary>
public sealed class DemographicPhoneNumberRequiredCheck : ValidationAttribute
{
public override bool IsValid(object value)
{
???????
}
}
Thanks.
Upvotes: 3
Views: 156
Reputation: 70718
You could use Count
or Any
:
public override bool IsValid(object value)
{
var PhoneNumbers = value as List<Phone>;
if (PhoneNumbers != null)
{
return PhoneNumbers.Count() > 0;
}
return false;
}
Or:
public override bool IsValid(object value)
{
var PhoneNumbers = value as List<Phone>;
if (PhoneNumbers != null)
{
return PhoneNumbers.Any();
}
}
Upvotes: 3
Reputation: 13513
Actually you have the value in your method:
public override bool IsValid(object value)
{
var phoneNumbers = value as List<Phone>;
if(phoneNumbers != null)
{
// perform the validation
}
}
Upvotes: 1