I have a property with StringLength attribute, but I can assign a string of any length to this property. I created the following test program in VB.NET 4.7 Framework:
Imports System.ComponentModel.DataAnnotations
Module Module1
Class C1
<StringLength(3)>
Public Property BufferId As String
End Class
Sub Main()
Dim c1 = New C1
c1.BufferId = "abcd"
Console.WriteLine($"c1.BufferId={c1.BufferId}")
Console.ReadKey()
End Sub
End Module
Although StringLength=3, I am able to assign a string of length 4.
How can I make the StringLength attribute to throw an exception, when I assign a string of length longer than the specified length?
Attributes are (with a few exceptions for compiler-interpreted attributes) passive annotations; they don't do anything unless some code (usually a library such as an ORM or UI toolkit, or a Roslyn analyzer) looks for them, and makes some decisions based on their existence.
If you want to validate things: a property setter can help. I can't remember much VB, but in C# terms:
You can of course write your own utility methods to simplify this, allowing things like