One of the fields must be required - Dataannotation

Asked

Viewed 708 times

1

Code example:

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 one of the fields CPF or CNPJ (or it fills CPF, or it fills CNPJ). How can I do this with DataAnnotation?

  • 2

    Just out of curiosity, since you’re going to use it as string why not use the same field?

  • @jbueno, can you give me an example ?

  • @Matheusmiranda ééér, use only one field for two things(?)

  • @jbueno, that’s right

1 answer

4


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" });
        }
    }
}
  • 1

    Interesting, I didn’t know that.

  • You enter a blank and the other correct and it doesn’t validate, is that it? Have you tried debugging the Validate?

  • 1

    @Matheusmiranda It was bad. It’s done. Thank you!

  • Put a breakpoint in the first if and see what happens. jQuery Validate is correct so far.

  • 1

    Cool. You can use both together. Just need to improve the configuration.

Browser other questions tagged

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