How To Disable Validation When Editing a Web Part

When you edit a Web Part that embbed a form with required fields you have troubles to save you changes. The solution is to check the current display mode of your WebPart and – in case of edition – disable the validation on controls.

I use the following snippet in one of my SharePoint project. The WebPart uses a User Control that embbed the form which contains required fields. Here is the code of the CreateChildControls method of my Web Part class:

private const string _ascxPath = @"~/_CONTROLTEMPLATES/MyProject/MyUserControl.ascx;

protected override void CreateChildControls()
    Control control = Page.LoadControl(_ascxPath);
    WebPartManager wp = WebPartManager.GetCurrentWebPartManager(Page);
    if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit
        || SPContext.Current.FormContext.FormMode == SPControlMode.New
        || wp.DisplayMode == WebPartManager.EditDisplayMode)