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.
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();
}
}
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.