Best way to implement DataAnnotations

1

Is there any difference in the following implementations?

 [Required, StringLength(150, ErrorMessage = "Insira no máximo 150 caracteres")]
 [Index(IsUnique =true)]
 public int MyProperty { get; set; }

 [Required]
 [StringLength(150, ErrorMessage ="Insira no máximo 150 caracteres")]
 [Index(IsUnique =true)]
 public int MyProperty { get; set; }

I ask in order to know, if there are moments that are used the first way and in others of the second. Or is it the same thing?

    
asked by anonymous 22.12.2016 / 02:27

2 answers

3

Just to note, the answer is valid for all types of attributes and not just DataAnnotations .

There is no functional difference between the two statements.

It's more a matter of liking "style" than programming.

Most of the time, I would rather use the attributes on the same line, unless they have very big names or I end up using many parameters, lines for easy reading.

Then:

[PrimeiroAtributo, SegundoAtributo]
public string Nome { get; set; }

It's exactly the same as

[PrimeiroAtributo]
[SegundoAtributo]
public string Nome { get; set; }
    
22.12.2016 / 03:49
3

If you just leave it like this:

[Required, StringLength(150, ErrorMessage = "Insira no máximo 150 caracteres")]

The custom message will fire only for the string with the maximum length of 150 characters. And so it will be the same

[Required]
[StringLength(150, ErrorMessage ="Insira no máximo 150 caracteres")]

If you are using jquery validate, a default message will be issued for Required, but if you want to leave the custom message:

[Required(ErrorMessage = "O campo xxx deverá ser preenchido!)]

And I think the best way is to use it as in the example:

public class Produto
{
    [Key]
    [Column(Order = 0)]
    public int ID { get; set; }

    [Required(ErrorMessage = "Digite o nome do produto."), Column(Order = 1)]
    [MinLength(5, ErrorMessage = "O tamanho mínimo do nome são 5 caracteres.")]
    [StringLength(200, ErrorMessage = "O tamanho máximo são 200 caracteres.")]
    public string Nome { get; set; }

    [Display(Name="Quantidade")]
    [DisplayFormat(DataFormatString = "{0:n2}",
            ApplyFormatInEditMode = true,
            NullDisplayText = "Estoque vazio")]
    [Range(10, 25, ErrorMessage = "A Qtde deverá ser entre 10 e 25.")]
    [Column(Order = 2)]
    public double Qtde { get; set; }

    [DisplayFormat(DataFormatString = "{0:n2}",
            ApplyFormatInEditMode = true,
            NullDisplayText = "Sem preço")]
    [Range(3, 500, ErrorMessage = "O preço deverá ser entre 3 e 500.")]
    [Column(Order = 3)]
    public decimal Preco { get; set; }

    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    [Column(Order = 4)]
    [Display(Name="Vencimento")]
    public DateTime Dt_Vencto { get; set; }
}
    
22.12.2016 / 02:48