Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataAnnotations MaxLength and StringLength for string[] or List<string>?

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.

like image 226
GCymbala Avatar asked May 19 '14 19:05

GCymbala


People also ask

What is DataAnnotations MaxLength attribute?

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 size of string in C#?

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.

What is System ComponentModel DataAnnotations?

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.

Which data annotation value specifies the max and min length of string with error?

The StringLength Attribute Specifies both the Min and Max length of characters that we can use in a field.


2 Answers

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

like image 132
musium Avatar answered Sep 23 '22 10:09

musium


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;
    }
}
like image 39
Sasan Avatar answered Sep 24 '22 10:09

Sasan