When you create a custom form you may want to have code behind to evaluate the user’s data entry based on some business logic before the object is created/updated.  To demonstrate how to do this I have extended the Service Request CodePlex project to provide a simple example of form validation.

In the code behind for the Service Request form, we already had added an Event  Handler for the PreviewSubmitEvent

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.AddHandler(FormEvents.PreviewSubmitEvent, new EventHandler<PreviewFormCommandEventArgs>(this.OnPreviewSubmit));
        }

This event is called when the user clicks the OK button on a form.  It allows you to do some last minute validation or property manipulation before the object is saved to the database.  Originally I just had a piece of code in there that would take the Title the user entered and concatenate that together with the work item ID to form the Display Name value for the service request like this:

itemServiceRequest["DisplayName"] = itemServiceRequest["Id"] + " - " + itemServiceRequest["Title"];

Now, let’s say I only want to allow the user to save the service request if they have provided a Title value.  I can do that like this:

        private void OnPreviewSubmit(object sender, PreviewFormCommandEventArgs e)
        {
            /* NOTE: The use of the IDataItem interface here is not supported/documented.
            * This interface may change in the future and no migration path is guaranteed by Microsoft.
            */
            IDataItem itemServiceRequest = this.DataContext as IDataItem;
            if (String.IsNullOrEmpty(this.txtTitle.Text.Trim()))
            {
                e.Cancel = true;
                MessageBox.Show("Please provide a title"); 
            }
            else
            {
                itemServiceRequest["DisplayName"] = itemServiceRequest["Id"] + " - " + itemServiceRequest["Title"];
            }
        }

This is how you can hook up whatever form validation you want to do.  Just include it in the event handler for the PreviewSubmitEvent event and if it fails validation set the PreviewFormCommandEventArgs.Cancle = true.  The default for PreviewFormCommandEventArgs.Cancel is false so unless you set it to true it will go through.

With this code in place if the user doesn’t enter a Title the user will see a warning message box like this:

image

The form will stay open so the user can fix any validation errors and nothing will be saved to the database yet.  Once the user provides a title and clicks OK the form will close and the object will be updated in the database.

The change list #82264 contains the latest code sample.