Try our conversational search powered by Generative AI!

How to check if there are elements in IList?

Vote:
 

I want to put a validation on IList to check if there are elements added in the ILIst.

If no elements present, I wan to show a validation message saying "Please add values in the list".

public virtual IList<QuestionnaireAnswerBlock> Answers { get; set; }

Please help.

#224815
Jun 26, 2020 12:56
Vote:
 

Hi Tanvi,

Make it required

[required]
public virtual IList<QuestionnaireAnswerBlock> Answers { get; set; }

And if you want to customize the validation message then create a custom validation attribute. The solution I mentioned in your other question

https://world.episerver.com/forum/developer-forum/-Episerver-75-CMS/Thread-Container/2020/6/how-to-limit-number-of-elements-in-ilist-with-only-minimum-elements-value/

#224818
Edited, Jun 26, 2020 13:30
Vote:
 

As Ravindra suggested you can just use a required attribute.

Or, if you want to be able to valdiate a specific number of items, how about a validation attribute like this:

[AttributeUsage(AttributeTargets.Property)]
public class MinItemsAttribute : ValidationAttribute
{
	private readonly int _minAllowed;

	public MinItemsAttribute(int minAllowed)
	{
		_minAllowed = minAllowed;
	}

	protected override ValidationResult IsValid(object value, ValidationContext validationContext)
	{
		var linkItemCollection = value as LinkItemCollection;

		if (linkItemCollection != null && ValidateMinAllowed(linkItemCollection.Count))
		{
			return ValidationResult.Success;
		}

		var contentArea = value as ContentArea;

		if (contentArea?.Items != null && ValidateMinAllowed(contentArea.Count))
		{
			return ValidationResult.Success;
		}

		var enumerable = value as IEnumerable;

		if (enumerable != null && ValidateMinAllowed(enumerable.Cast<object>().Count()))
		{
			return ValidationResult.Success;
		}

		return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
	}

	private bool ValidateMinAllowed(int count)
	{
		return count >= _minAllowed;
	}

	public override string FormatErrorMessage(string name)
	{
		return !string.IsNullOrEmpty(ErrorMessage) ? ErrorMessage : $"{name} requires at least {_minAllowed} items.";
	}
}

It'll work on a Link Item Collection, Content Area or IList<>.

Using it is as simple as:

[MinItems(2)]
public virtual IList<QuestionnaireAnswerBlock> Answers { get; set; }

You can customize the error message as well:

[MinItems(2, ErrorMessage = "Please add at least 2 values to the list")]
public virtual IList<QuestionnaireAnswerBlock> Answers { get; set; }
#224819
Edited, Jun 26, 2020 14:15
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.