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: https://world.episerver.com/documentation/developer-guides/CMS/Content/Properties/built-in-property-types/Writing-custom-attributes/
/// <summary>
/// Required field validation for Category.
///Reference: https://world.episerver.com/documentation/developer-guides/CMS/Content/Properties/built-in-property-types/Writing-custom-attributes/
/// </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.
[Display(
Name = "News Category (*)",
Description = "Select News Category",
GroupName = SystemTabNames.Content,
Order = 3)]
[FieldRequiredForPublish]
public override CategoryList Category { get; set; }
The code is generic enough that you can extend to make any field requied.
Thank you & happy coding!
Comments