Siraj Hussain
Siraj Hussain

Reputation: 874

MVC3 Custom validation

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

Answers (2)

Darren
Darren

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

Kaveh Shahbazian
Kaveh Shahbazian

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

Related Questions