Tuesday, November 14, 2006

Custom validation for core properties

Last week a colleague of mine asked a question:

Is it possible to limit the amount of data that can be entered into EPiServer text properties?

Now this can be achieved in a number of ways. First, if the property is one you have added, then you can just create a custom property and add whatever type of validation you like, pretty standard stuff. However, if the property is a core property such as "PageName", then you have capture the "EditPageValidators" event in the EPiServer.Global class.

Here is an example I have used for a few clients now to validate the "PageName" to set a maximum number of characters. This same implementation can be used to perform any custom validation against core properties in EPiServer.

In the global.asax, hook the following up in the Application_Start method:

Global.EditPageValidators += new PageValidateEventHandler(Validators.ValidatePageNameLength);

The implementation for ValidatePageNameLength is the following:

public static void ValidatePageNameLength(object sender, PageValidateEventArgs e)
{
int length = (int)Global.EPConfig["EPnMaxPageNameLength"];
if( e.Page.PageName.Length > length && length > 0 )
{
e.IsValid = false;
e.ErrorMessage = String.Format( "\"Name\" must not exceed {0} characters", length );
}
}


This then requires a web.config key of “EPnMaxPageNameLength” to configure the number of characters in the PageName property.

3 comments:

Anonymous said...

It's Global.ValidatePageNameLength in 4.61. Thanks!

Jeremy said...

It depends on where you put the validation method. I had mine in a separate class called Validators. Thanks for spotting the problem ;)

Anonymous said...

Ah, right. :) Cheers!