How to use IValidatableObject?

9

How do I use IValidatableObject to not validate a foreign key property during a registration? I want to validate only the foreign key in the edit.

    
asked by anonymous 27.10.2015 / 02:11

1 answer

9

IValidatableObject asks to implement Validate , which is a method that takes as its argument a ValidationContext .

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    /* Aqui entra a validação em si */
}

For your case, as you just want to validate in the edit, this means that the primary key is filled. So the logic would look like this:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if (this.EntidadeId != null && this.EntidadeId > 0) {
        if (this.EntidadeEstrangeiraId == null || this.EntidadeEstrangeiraId <= 0) {
            yield return new ValidationResult("É necessário definir um valor de EntidadeEstrangeira", new [] { "EntidadeEstrangeiraId" });
        }
    }
}
    
27.10.2015 / 02:29