AlexK AlexK - 2 years ago 119
C# Question

Array size validation in C#

I have a controller method with array of integers input, which must not be null or more than 10 elements size. To validate input I 've made a class:

public class TestForm
{
[Required]
[MaxLength(10)]
public long[] feedIds { get; set; }
}


And controller method:

[HttpPost]
public async Task<IActionResult> DoSomeJob(TestForm form)
{
//Do some job
}


According to MSDN,
System.ComponentModel.DataAnnotations.MaxLength
can be used for array, but there is no validation, it gets null and array of any size. What am I doing wrong?

Answer Source

Here is what we use in one of our projects:

public class LengthAttribute : ValidationAttribute {
    readonly int length;

    public LengthAttribute(int length) {
        this.length = length;
    }

    public override bool IsValid(object value) {
        if (value is ICollection == false) { return false; }
        return ((ICollection)value).Count == length;
    }
}

On a property like the following:

public class CreateUserApiRequest : ApiRequest {

    [DataMember]
    [Length(128)]
    [Description("クライアントキー")]
    public byte[] clientKey { get; set; }
    ....
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download