StringLength vs MaxLength attributes ASP.NET MVC w

2019-01-12 20:42发布

What is the difference in behavior of [MaxLength] and [StringLength] attributes?

As far as I can tell (with the exception that [MaxLength] can validate the maximum length of an array) these are identical and somewhat redundant?

7条回答
成全新的幸福
2楼-- · 2019-01-12 21:15

MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.

From MSDN:

Specifies the maximum length of array or string data allowed in a property.

StringLength is a data annotation that will be used for validation of user input.

From MSDN:

Specifies the minimum and maximum length of characters that are allowed in a data field.

查看更多
混吃等死
3楼-- · 2019-01-12 21:17

Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):

The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:

[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }

Will output the following if it is over the character limit: "Address can have a max of 100 characters"

The placeholders I am aware of are:

  • {0} = Property Name
  • {1} = Max Length
  • {2} = Min Length

Much thanks to bloudraak for initially pointing this out.

查看更多
相关推荐>>
4楼-- · 2019-01-12 21:17

MaxLengthAttribute means Max. length of array or string data allowed

StringLengthAttribute means Min. and max. length of characters that are allowed in a data field

Visit http://joeylicc.wordpress.com/2013/06/20/asp-net-mvc-model-validation-using-data-annotations/

查看更多
叼着烟拽天下
5楼-- · 2019-01-12 21:26

Following are the results when we use both [MaxLength] and [StringLength] attributes, in EF code first. If both are used, [MaxLength] wins the race. See the test result in studentname column in below class

 public class Student
 {
    public Student () {}

    [Key]
    [Column(Order=1)]
    public int StudentKey { get; set; }

    //[MaxLength(50),StringLength(60)]    //studentname column will be nvarchar(50)
    //[StringLength(60)]    //studentname column will be nvarchar(60)
    [MaxLength(50)] //studentname column will be nvarchar(50)
    public string StudentName { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }
 }
查看更多
男人必须洒脱
6楼-- · 2019-01-12 21:28

One another point to note down is in MaxLength attribute you can only provide max required range not a min required range. While in StringLength you can provide both.

查看更多
劫难
7楼-- · 2019-01-12 21:31

All good answers...From the validation perspective, I also noticed that MaxLength gets validated at the server side only, while StringLength gets validated at client side too.

查看更多
登录 后发表回答