How do I get an Annotation date, to be able to access value from another property?

Asked

Viewed 490 times

2

I have my following properties:

public ETipoPessoa TipoPessoa {get;set;}
public string CnpjCPF {get;set;}

public enum ETipoPessoa {
     Fisica,
     Juridica
}

I have this condition, if Type = Physical, I need to pass an Annotation that validates the CPF, otherwise Type = Legal validate the CNPJ

So, as I do an Annotation date, I can access value from another property ?

That is, my Annotation has to take the value that came from the Typopessoa, to validate what is what...

  • CPF always has 11 digits. CNPJ always has 14. O TipoPessoa is not necessary.

  • Required in View for mask

  • You can put the field without necessarily mapping it into the database, since the mask is important.

  • Gypsy, in my opinion it is very important to have mapped, even more when we filter by "Type"

1 answer

3

It is not yet what you want, but there is a way to make a validation at the level of the Model.

public class Pessoa : IValidatableObject
{
    public ETipoPessoa TipoPessoa {get;set;}
    public string CnpjCPF {get;set;}

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var validations = new List<ValidationResult>();

        if (TipoPessoa == ETipoPessoa.Fisica)
        {
            bool cpfValido;
            ... // validação de CPF
            if (!cpfValido)
                validations.Add(new ValidationResult("CPF Inválido"));
        }

        if (TipoPessoa == ETipoPessoa.Juridica)
        {
            bool cnpjValido;
            ... // validação de CNPJ 
            if (!cnpjValido)
                validations.Add(new ValidationResult("CNPJ Inválido"));
        }
        return validations;
    }
}
  • I think it would be nice if you put inside each if how to fire an error message to the Controller.

Browser other questions tagged

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