Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply Required attribute on Composite Model?

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

I have a field in my model named PersonDetails

public Phone PhoneDetails{get;set;}

Phone is another model containing three other fields as

int MobilePhone;
int WorkPhone;
int HomePhone;

PersonDetails is a model which I am passing to add popup. PersonDetails has following field :

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

I can apply Required Field attribute to remaining fields, but I want to apply Required attribute to PhoneDetails field. The condition is that at least one of the three i.e. MobilePhone,WorkPhone or HomePhone should have a value.

How can I solve this problem?

like image 520
Amol Eklare Avatar asked Nov 02 '22 23:11

Amol Eklare


1 Answers

One approach would be 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" });
    }
}

Your form will then show "Please enter at least 1 phone number" if none are entered.

like image 176
David Duffett Avatar answered Nov 12 '22 14:11

David Duffett