How to: Show Validation Errors when IDataErrorInfo is Used

  • 3 minutes to read

This document describes how to display validation errors in the application you created with the DevExpress Scaffolding Wizard.

Assume you have a simple entity that supports the IDataErrorInfo interface.

public class Department : IDataErrorInfo {
        public int DepartmentID { get; set; }
        public string Name { get; set; }
        public decimal Budget { get; set; }
        public DateTime StartDate { get; set; }

        public string Error {
            get {
                return this["Name"] != null || this["Budget"] != null ? "Correct values" : null;
            }
        }

        public string this[string columnName] {
            get {
                switch(columnName) {
                    case "Name":
                        return string.IsNullOrEmpty(Name) ? "Name cannot be null" : null;
                    case "Budget":
                        return Budget < 0 ? "Budget cannot be negative" : null;
                    default:
                        return null;
                }
            }
        }
    }

First, generate an application using the Scaffolding Wizard as described in the first lesson of the following tutorial: Building Office-Inspired Applications.

To display data items, the Scaffolding Wizard generates DataLayoutItem objects that, in turn, generate editors in runtime.

<dxlc:DataLayoutItem Label="Name" Name="layoutItemName" Binding="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />

After completing the initial steps, validation errors will be displayed in the following manner.

scaffolding_validation_01

In most cases, saving the changes to a database should be prohibited if the entity supports the IDataErrorInfo interface and there data errors in the entity. The generated application supports this scenario out of the box. If you want to allow the end user save changes even if there data errors or implement your own validation logic, override the HasValidationErrors method generated by the Scaffolding Wizard.

partial class SingleObjectViewModel<TEntity, TPrimaryKey, TUnitOfWork> {
        protected override bool HasValidationErrors() {
            return false;
        }
    }

If the HasValidationErrors method returns true, the Save button will be disabled. Additionally, when pressing the Close button, a modal warning dialog will appear with only two buttons: OK and Cancel.

scaffolding_validation_02

TIP

A complete sample project is available in the DevExpress Code Examples database at http://www.devexpress.com/example=T111378.