0

I have:

public class Test
{
    [Required]
    public string Name { get; set; }

    [Required]
    public bool Is1 { get; set; }

    [RequiredIfTrue("Is1")]
    public string Name2 { get; set; }

    public Person Person { get; set; }

    [RequiredIf("Person", Operator.EqualTo, Person.Pirate)]
    public Test2 PirateAge { get; set; }
}

public enum Person
{
    Student = 0,
    Child = 1,
    Pirate = 2
}

public class Test2
{
    public string Name { get; set; }
}

Test is a complex model which has Test2 model. I want to make Name property of Test2 be required if Person is Pirate.

How can I do it? Maybe another solution.

Dmitry
  • 477
  • 6
  • 20
  • Create a view model with a flat structure containing all properties (not containing models) - you cannot apply the validation attribute to a complex object because you do not (cannot) generate a form control for it, only for properties of it. –  Mar 31 '16 at 08:57
  • @StephenMuecke if I want to have several properties of Test2 and one of them should be required all time and second depend on some enum property as at my example. – Dmitry Mar 31 '16 at 09:15
  • Thats exactly why you should have a view model - combining all properties from `Test` and `Test2`. –  Mar 31 '16 at 09:18
  • Another option is to perform validation in your controller. Should it fail validation then add an error to ModelState. This does not give you client side validation but it will allow you to keep your existing structure. – TheEdge Mar 31 '16 at 10:10

0 Answers0