How to use Ivalidatableobject?

Asked

Viewed 188 times

9

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

1 answer

9


IValidatableObject asks to implement Validate, which is a method that takes as an 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 editing, this means that the primary key is filled in. 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" });
        }
    }
}
  • 1

    Legal, is similar to Fluentvalidation, I’m going to use in this project. Thanks a lot!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.