MaxLength DataAnnotation Attribute in Asp.net MVC3 Razor

  1. MaxLength Attribute ensures the length of the string entered is according to the specified value.
  2. System will through an error if the string length entered is greater than the MaxLength specified.
  3. In order to use this attribute, you have to include System.ComponentModel.DataAnnotation reference.
Example 1 :


The above syntax has applied MaxLength attribute to LastName property. If user enters LastName greater than 10, the validation fails and an error is thrown. In the above case as we have not specified the error message system will show the default error message.

UI :


In the above screenshot we have entered LastName greater than 10. The validation fails for the LastName on posting the form and error message is shown. 


Example 2 :


In this example, we have also specified the custom error message, so that when the validation fails this message is shown instead of default error message.


UI :


As we can see, the validation fails in above case and our error message is displayed.


Example 3 :


In the above example, we are picking the error message from resource file. The above excepts a resource file with name Multi with key MaxLength_ErrorMessage holding the error message. When validation fails, the system picks error message from resource file.

Resource :


UI :



Example 4 :


In the above example, we have not specified the MaxLength. In this case it verifies the string length with the database and throws an error if user enters more than what is expected in Database. 

0 comments:

Post a Comment