Easily Sanitize a Sitecore Item Name in C#

Say you’re creating a new Sitecore item programmatically in C#. The general approach is to take some piece of data from your original data point, e.g. an article in a feed, and sanitize it so your item name is valid in Sitecore. Let’s take the example of an article’s title. Most developers will strip out the invalid character’s they can think would cause issues in Sitecore, e.g. !,.:; etc…

Here’s an easier way to do it with Sitecore’s own configuration:

char[] invalidcharacters = Sitecore.Configuration.Settings.InvalidItemNameChars;
string sanitizedName = string.Concat(possibleName.Trim().Split(invalidcharacters));

Notice Sitecore.Configuration.Settings.InvalidItemNameChars gives you a character array of the characters defined in the web.config. From there, we just trim whitespace away from the name, split the string at each “invalid” character and then concatenate the split chunks.

For re-usability, here it is as an overloaded extension method:

public static string SanitizeToItemName(this string possibleName)
{
  return SanitizeToItemName(possibleName, Sitecore.Configuration.Settings.InvalidItemNameChars);
}

public static string SanitizeToItemName(this string possibleName, char[] invalidCharacters)
{
  return string.Concat(possibleName.Trim().Split(invalidCharacters));
}

UPDATE:

Mark van Aalst identified that the Sitecore API has a utility method that does something like this already: Sitecore.Data.Items.ItemUtil.ProposeValidItemName(name, defaultValue);. Thanks for the tip Mark!

 

Mark Ursino

Mark is Sr. Director, CMS Practice Lead at Rightpoint and a Sitecore Technology MVP.

 

4 thoughts on “Easily Sanitize a Sitecore Item Name in C#

  1. There is also a method called ProposeValidItemName within the Sitecore.Data.Items.ItemUtil class which does the same. It also has an overload for a default value.

    string itemName = ItemUtil.ProposeValidItemName(name, defaultValue);

Leave a Reply

Your email address will not be published. Required fields are marked *