Five New Optimizely Certifications are Here! Validate your expertise and advance your career with our latest certification exams. Click here to find out more

Aniket
Oct 7, 2018
  7112
(3 votes)

Max & Min element validation for Content Area or Link Collection

Reccently we had a business requirement for setting minimum & maximum limit for blocks in Content Areas. While we can educate the content authors to set the correct number of blocks in the content area it's always recommended to add validation within the CMS to avoid human errors.

Here's the code to to set the maximum number of blocks in the content area and Link Item Collection. 

/// <summary>
    /// Sets the maximum element count in a linkcollection, a content area - or any other type of collection.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class MaxElementsAttribute : ValidationAttribute, IMetadataAware
    {
        public int MaxCount { get; set; }

        public void OnMetadataCreated(ModelMetadata metadata)
        {
            //TODO: Use to disable editor drag and drop at a certain point.
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
            {
                return null;
            }
            if (value is LinkItemCollection)
            {
                if ((value as LinkItemCollection).Count > MaxCount)
                {
                    return new ValidationResult("This field exceeds the maximum limit of " + MaxCount + " items");
                }
            }
            else if (value is ContentArea)
            {
                if ((value as ContentArea).Count > MaxCount)
                {
                    return new ValidationResult("This field exceeds the maximum limit of " + MaxCount + " items");
                }
            }

            return null;
        }

        public MaxElementsAttribute(int MaxElementsInList)
        {
            this.MaxCount = MaxElementsInList;
        }
    }

On the Content Area field (or Link Item Collection) set the MaxElements attribute as shown below. 

[Display(
            Name = "Items",
            Description = "Items",
            GroupName = SystemTabNames.Content,
            Order = 30)]
        [MaxElements(25)]
        public virtual ContentArea Items { get; set; }

You can use the same logic for setting the minimum number of elements as well. 



Happy coding :)

Oct 07, 2018

Comments

Antti Alasvuo
Antti Alasvuo Oct 9, 2018 05:49 AM

Hi Aniket, first thanks for sharing this.

You should use the 'is' pattern matching in the code, see the docs. Now you first test is the value of some type (casting) and then if it was successful then the code casts again the object.

The XML comment says that it handles 'any other type of collection' but there is no implementation for collections in the code you have provided.

Please login to comment.
Latest blogs
Extending UrlResolver to Generate Lowercase Links in Optimizely CMS 12

When working with Optimizely CMS 12, URL consistency is crucial for SEO and usability. By default, Optimizely does not enforce lowercase URLs, whic...

Santiago Morla | Mar 7, 2025 |

Optimizing Experiences with Optimizely: Custom Audience Criteria for Mobile Visitors

In today’s mobile-first world, delivering personalized experiences to visitors using mobile devices is crucial for maximizing engagement and...

Nenad Nicevski | Mar 5, 2025 |

Unable to view Optimizely Forms submissions when some values are too long

I discovered a form where the form submissions could not be viewed in the Optimizely UI, only downloaded. Learn how to fix the issue.

Tomas Hensrud Gulla | Mar 4, 2025 |

CMS 12 DXP Migrations - Time Zones

When it comes to migrating a project from CMS 11 and .NET Framework on the DXP to CMS 12 and .NET Core one thing you need to be aware of is the...

Scott Reed | Mar 4, 2025

New Optimizely Certifications – Take Your Skills to the Next Level

Big news! We’ve just launched five new Optimizely certifications to help you validate your skills and stand out in the world of digital experience...

Satata Satez | Feb 28, 2025

Optimizely Graph Cache: The Power of "Item"

In the world of content delivery, speed is king. A high cache hit ratio is the secret weapon for delivering snappy performance and happy users. But...

Jonas Bergqvist | Feb 28, 2025