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:
[csharp]
char[] invalidcharacters = Sitecore.Configuration.Settings.InvalidItemNameChars;
string sanitizedName = string.Concat(possibleName.Trim().Split(invalidcharacters));
[/csharp]
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:
[csharp]
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));
}
[/csharp]
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!
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);
Thank you for sharing.
This is really helpful
Thanks Mark! Didn’t know that existed — definitely going to be using that much more.
Hilariously, the defaultValue parameter of the ProposeValidItemName function is never used. Instead, ItemUtil.DefaultItemName is used when a valid item name can’t be created.
The fact that no one has ever noticed this probably means that it’s pretty much always possible to create a valid item name 🙂