One of the fields must be mandatory - DataAnnotation [duplicate]

1

Code sample:

Model:

[Required(ErrorMessage = "Campo CPF ou CNPJ obrigatório")]
[Display(Name = "CPF")]
public string CPF { get; set; }

[Display(Name = "CNPJ")]
public string CNPJ { get; set; }

User must fill in one of the CPF or CNPJ fields (either he fills in the CPF, or he fills in the CNPJ). How can I do this with DataAnnotation ?

    
asked by anonymous 24.04.2017 / 22:04

1 answer

4

It is not decorated by attributes that you will solve. Implement IValidatableObject in 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" });
        }
    }
}
    
24.04.2017 / 22:17