I am trying to figure out if there is a proper way to achieve this with DataAnnotations:
Have an array or List of strings where the maximum number of elements in the array or List is 2 items and where each string may only be, say 255 characters long. Will this work:
[MaxLength(2)]
[StringLength(255)]
public string[] StreetAddress { get; set; }
I would rather not have to make a new class just to hold a string Value
property to constrain each string to 255 characters.
Data Annotations - MaxLength Attribute in EF 6 & EF Core The MaxLength attribute specifies the maximum length of data value allowed for a property which in turn sets the size of a corresponding column in the database. It can be applied to the string or byte[] properties of an entity.
What is the max string length in C#? The maximum string length in C# is 2^31 characters. That's because String. Length is a 32-bit integer.
Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.
The StringLength Attribute Specifies both the Min and Max length of characters that we can use in a field.
You can create your own validation attribute by inheriting from Validation Attribute like described here: How to: Customize Data Field Validation in the Data Model Using Custom Attributes
This is a custom attribute for list of strings:
public class StringLengthListAttribute : StringLengthAttribute
{
public StringLengthListAttribute(int maximumLength)
: base(maximumLength) { }
public override bool IsValid(object value)
{
if (value is not List<string>)
return false;
foreach (var str in value as List<string>)
{
if (str.Length > MaximumLength || str.Length < MinimumLength)
return false;
}
return true;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With