Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net mvc dataannotation MaxLength validation does not work

Tags:

I am using asp.net mvc4 in my model i am using Maxlength attribute but it does not work for string. Only Stringlength works anyone have same problem ? if had issue how to resolve ? it does not work for validate my field Here is my code

(not working)

[Required] [MaxLength(80)] [DisplayName("Contact Name:")] public string ContactName { get; set; } 

(working)

[Required] [StringLength(80)] [DisplayName("Contact Name:")] public string ContactName { get; set; } 
like image 629
Garry Avatar asked Jan 31 '13 15:01

Garry


1 Answers

Both Attributes are in System.ComponentModel.DataAnnotations namespace

As per Microsoft Official Website [MaxLength] attribute in for Entity Framework because Entity Framework knows what can be the maximum length of the column in the database in your case(like varchar(80))

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

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.maxlengthattribute.aspx

As in one of you comment you have said you are not using Entity Framework in reply with @jackncoke so [MaxLength(80)] will not work

But in second case [StringLength(80)] is working because it does not have any dependency over Entity Framework.

SO [StringLength(80)] will work in both cases if you are using Entity Framework or without it

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

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.stringlengthattribute.aspx

like image 80
Pamma Avatar answered Sep 28 '22 03:09

Pamma