Array Length validation?

Topics: Validation Application Block
Apr 23, 2008 at 1:17 AM
Edited Apr 23, 2008 at 6:12 PM
Is there a way to the validate the number of items in an array? I've tried the RangeValidator but it fails with the message: "System.NotSupportedException: ArrayConverter cannot convert from System.String.." The field I'm trying to validate is an int array (int[]). I've been poking around the validation code and can't find what I'm looking for.

Has anyone ever done this?

May 12, 2008 at 6:23 PM
I second this request.  It seems like an obvious one to me, and i can't find a way to do it.

May 13, 2008 at 4:11 PM
Edited May 13, 2008 at 4:13 PM
Hope this code snippet will help:


RangeValidator rv = new RangeValidator(0, RangeBoundaryType.Inclusive, 4, RangeBoundaryType.Inclusive, "ArrayLength Error", false);
ValidationResults vr = new ValidationResults();
String[] myArr = new String[] { "a", "b", "c", "d" };
.Validate(myArr.Length, vr);
String testresult = "Testresult:";

foreach (ValidationResult r in vr)
+= "\n" + ":\n" + r.Message + "\n";




May 13, 2008 at 11:26 PM

There is no built-in array length validator in the Validation Block. A self-validation message may work in your case, otherwise you'll need a custom validator.

To create a custom validator, you can inherit from ValueValidator and you'll be forced to implement the required methods. You need to provide a constructor that takes a NameValueCollection as its only parameter, so you can specify it in the configuration console, and you will probably want to define a matching attribute inheriting from ValueValidatorAttribute so you can use it declaratively without configuration.

May 14, 2008 at 1:13 AM
I ended up creating my own custom validator "ArraySizeValidator" that is based largely on the existing RangeValidator.  I would suggest that anyone wanting to do the same should start there as it already contains the boundry validation code.  All you have to write the is the NameValueCollection reader and the actual DoValidate function.

Hopefully upcoming versions of Enterprise Library will include this validator as it certainly is what I would consider to be a "base" type validator.