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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With