It is not with decoration by attributes that you will solve. Implement IValidatableObject
in the Model:
public class MeuModel : IValidatableObject
{
...
[Display(Name = "CPF")]
public string CPF { get; set; }
[Display(Name = "CNPJ")]
public string CNPJ { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (String.IsNullOrEmpty(CPF) && String.IsNullOrEmpty(CNPJ))
{
yield return new ValidationResult("É necessário definir ou CPF ou CNPJ.", new [] { "CPF", "CNPJ" });
}
if (!String.IsNullOrEmpty(CPF) && !String.IsNullOrEmpty(CNPJ))
{
yield return new ValidationResult("CPF e CNPJ não podem ambos ter valor.", new [] { "CPF", "CNPJ" });
}
}
}
Just out of curiosity, since you’re going to use it as
string
why not use the same field?– Jéf Bueno
@jbueno, can you give me an example ?
– Matheus Miranda
@Matheusmiranda ééér, use only one field for two things(?)
– Jéf Bueno
@jbueno, that’s right
– Matheus Miranda