2009年4月5日 星期日

Validator control in webpart

Sometimes we'll create a webpart that contains ASP.Net control and maybe we'll add some validator contorl in this webpart.In your publishing page, you add that webpart and click publish, and maybe you'll get a error message:
This page contains content or formatting that is not valid. You can find more information in the affected sections.

This error message cause from the validator control in this webpart. However, you won't those validator will cause when you click save as a draft /check in / publish. How could we avoid this error occur?

  1. Check webpart mode
    Check if the web part is in edit or design mode and only add the validator if not:
    if (this.WebPartManager.DisplayMode != WebPartManager.EditDisplayMode && this.WebPartManager.DisplayMode != WebPartManager.DesignDisplayMode)
    {
    // in display mode(I add validator control in here)
    }
  2. using the SPContext.Current.FormContext.FormMode.
    // check if the form is in display mode
    bool inDisplayMode = SPContext.Current.FormContext.FormMode == SPControlMode.Display;
    protected override void CreateChildControls()
    {
    base.CreateChildControls();// Add the text box and validator
    bool inDisplayMode = SPContext.Current.FormContext.FormMode == SPControlMode.Display;
    if (inDisplayMode
    {
    // in display mode(I add validator control in here)
    }
    }