Views: 2895
Number of votes: 0
Average rating:

Required Field Validation for Category

We all have come across specific requirements for CMS Content authors. One of such requirement for our news sections is, "Every news article belongs to one or more categories". We must force user to select a category before publish it. We have used a Custom validation rule to fulfill this requirement.

Episerver Documentation:

  /// <summary>
     /// Required field validation for Category.
    /// </summary>

  [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class FieldRequiredForPublishAttribute : ValidationAttribute
        public bool IsRequired { get; set; }
        public FieldRequiredForPublishAttribute() : this(true) { }
        public FieldRequiredForPublishAttribute(bool isRequired)
            IsRequired = isRequired;

        public override bool IsValid(object value)
            if (value == null) return false;        
            if (value is CategoryList cat) return cat?.Any() == true;          
            return false;

        public override string FormatErrorMessage(string name)
                return $"{name} cannot be empty";

Set RequiredFieldAttribute for News Pages.

              Name = "News Category (*)",
              Description = "Select News Category",
              GroupName = SystemTabNames.Content,
              Order = 3)]
        public override CategoryList Category { get; set; }

 The code is generic enough that you can extend to make any field requied.

Thank you  & happy coding!

Oct 07, 2018

Stephan Lonntorp
( By Stephan Lonntorp, 10/8/2018 7:20:31 PM)

Why not use the built in RequiredAttribute from System.DataAnnotations?

Ram Kumar K
( By Ram Kumar K, 10/9/2018 11:43:11 AM)

When you are using "Required" built in functionality, you must enter "required" fields first in the content page. That would chnage the content fields order and may cause confusion. This validation occurs post content creation and before publishing the content. It would let authors save the content and won't publish until validation.

Antti Alasvuo
( By Antti Alasvuo, 10/9/2018 6:22:20 PM)

Just in case someone wants to use the RequiredAttribute but not show the fields when creating content then have also a look at Davids blog posting about hiding required properties when creating content. This approach needs less code to achieve the requirement: "don't show property on create content view but have the field required" BUT targeting only CategoryList type currently, so would need some additional code to cover various types.

Please login to comment.