How to apply a required attribute on a composite model?

I am using the Composite type for the field in the model.

I have a field in my model called PersonDetails

public Phone PhoneDetails{get;set;}

The phone is another model containing three other fields:

int MobilePhone;
int WorkPhone;
int HomePhone;

PersonDetails is the model I'm passing in to add a popup. PersonDetails has the following field:

public String Name{get;set;}
public Phone PhoneDetails{get;set;} 
public string Address{get;set;}

I can apply the RequiredField attribute to the remaining fields, but I want to apply the attribute Requiredto the field PhoneDetails. The condition is that at least one of the three, i.e. Mobile phones, work phones or a home phone should matter.

How can I solve this problem?

+5
source share
2 answers

One approach is to implement IValidatableObject:

public class PersonDetails : IValidatableObject
{
    public string Name { get; set; }
    public Phone PhoneDetails { get; set; }
    public string Address { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (PhoneDetails.MobilePhone == 0 && PhoneDetails.WorkPhone == 0 && PhoneDetails.HomePhone == 0)
            yield return new ValidationResult("Please enter at least 1 phone number", new[] { "PhoneDetails" });
    }
}

", ", .

+2

FluentValidation.

, /, MVC ( .NET- )

NuGet, - .

0

All Articles