0

I'm developing a little ERP to my company and I crashed into a problem about validation:

I have self property object like:

public class Person
{
   [Required]
   public string Name { get; set; }
   public int Phone { get; set; }
   public bool HasContact { get; set; }

   public Person Contact { get; set; }
}

If HasContact is false, I don`t want put a Contact. If is true, I want.

The problem is my ModelState never is Valid, because Name is Required and Contact self implement Person.

I would like to set condition if HasContact is true, my application try validate the Contact property. If is not, set Valid and execute controller correct.

Is it possible or am I crazy?

user921758
  • 21
  • 2
  • I'm very confused on the question. I'd recommend trying to explain it better. I am unsure of what your other classes are etc. – Ilan Keshet Jul 16 '18 at 20:48

1 Answers1

0

You should have your object implement IValidatableObject. It lets you implement your own validation logic so you can ignore properties as necessary (see this SO question).

Your code might be something like this:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    var results = new List<ValidationResult>();
    if (this.HasContact)
    {
        Validator.TryValidateProperty(this.Contact,
            new ValidationContext(this, null, null) { MemberName = "Contact" },
            results);
    }
    return results;
}
Becuzz
  • 6,846
  • 26
  • 39
  • Thanks for the reply... But, I'm not sure if this is the answer... If I use validate method every validation will blocked, correct? I will need make every validation manually. I want correct validate the Contact... Probably I didnt explane clearly my question... I will make some tests and Will return the results... Thanks again... – user921758 Jul 17 '18 at 01:42
  • If you implement `IValidatableObject` it hooks into the system already in place for doing validations. So you won't have to call `myObject.Validate(...)`. You would just do `if (ModelState.IsValid)` just like you always have. – Becuzz Jul 17 '18 at 16:03