SC 5.3: Ensure Item Names

Have you noticed that the names of your Sitecore Items in Sitecore 5.3 must follow certain expression rules? Danish letters (ÆØÅ) for example, are no longer allowed. The rules are expressed in the web.config setting called “ItemNameValidation” and “InvalidNameChars”. This can be used to verify wheter a string is allowed or not.

But sometines you wish to create your item even when the text string is invalid. In this case you will have to convert the string to a valid item name. The advanced option is to follow the regular expressions rules. The easy option is to just replace all non-standard characters with a standard one, and live with the new string.

This function does just that. Plus it will replace danish letters ÆØÅ with their 2-letter equvialent.

I was looking for this function in the Sitecore library but could not find one. So I made my own:

private string EnsureItemName(string text)
  // Allowed characters
  string validChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
  // Character to replace with when not-allowed char occurs
  char replaceChar = '';
  // Replace commonly used danish letters with their 2-letter equvivalent
  text = text.Replace("æ", "ae").Replace("ø", "oe").Replace("å", "aa").Replace("Æ", "Ae").Replace("Ø", "Oe").Replace("Å", "Aa");
  // Loop through the text string and replace invalid chars with the replaceChar
  foreach (char c in text)
    if (validChars.IndexOf(c) == -1)
      text = text.Replace(c, replaceChar);
  return text.Trim();

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in Sitecore 5 and tagged , , . Bookmark the permalink.

One Response to SC 5.3: Ensure Item Names

  1. Sander says:

    Very usefull! Add a text.Substring(0, 100) to the result and you have a fully legal Sitecore name.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.