1

I have a situation where I need to validate a child, but only if it exists. Basically the user can enter either a bank account or a credit card, and I only want to validate the one they enter.

Here are the Models:

public class AccountViewModel
{        
    [Required]
    public bool isBankAccount { get; set; }

    [RequiredIf("isBankAccount")]
    public BankAccount BankAccount { get; set; }

    [RequiredIf("isBankAccount",
        IfNot = true)]
    public CreditCard CreditCard { get; set; }
}

public class CreditCard
{
    [Required]
    [CreditCard]
    public string CreditCardNumber { get; set; }

    [Required]
    [Range(1, 12)]
    public int? ExpiryMonth { get; set; }

    [Required]
    [Range(2000, 3000)]
    public int? ExpiryYear { get; set; }

    [Required]
    public string CardHolderName { get; set; }
}

public class BankAccount
{
    [Required]
    public string BSB { get; set; }

    [Required]
    [StringLength(10,
        MinimumLength = 3)]
    [NumbersOnly]
    public string AccountNumber { get; set; }

    [Required]
    public string AccountHolderName { get; set; }
}

My problem is that the children's attributes are still being validated despite the parent attribute validating as true. Is there a way to stop the children from validating if the parent says so?

tereško
  • 58,060
  • 25
  • 98
  • 150
Ben Cull
  • 9,434
  • 7
  • 43
  • 38
  • 1
    Look at [validating dependent properties with Data Annotations](http://stackoverflow.com/questions/2280539/custom-model-validation-of-dependent-properties-using-data-annotations). – Darin Dimitrov Nov 18 '10 at 07:24

1 Answers1

0

Why not make a property PaymentMode , derive both Bank and CC from PaymentMode, make the field required, and handle it in UI as to what user can select and enter.

Just a thought.

Anuj Pandey
  • 938
  • 2
  • 11
  • 30