Skip to main content

How to: Restrict User Input in Date Editor

  • 2 minutes to read

The following example shows how you can restrict user input in a date editor. The user is able to enter dates between January 1 and December 31 of the current year. Other dates are not acceptable. If the user selects a date less than January 1, the edit value will be set to January 1. If the selected date is greater than December 31, the edit value will be set to the maximum possible date.

For this purpose, we will use the editor’s PopupBaseEdit.CloseUp event. Its handler is listed below.

Note that the user can enter the date in the edit box without activating the dropdown window. In this case, the PopupBaseEdit.CloseUp event is not fired, and therefore, no validation is performed. To prevent such situations, you can set the RepositoryItemButtonEdit.TextEditStyle property to TextEditStyles.DisableTextEditor. Another method is to handle the RepositoryItem.EditValueChanging event, to control edit value changes.

using DevExpress.XtraEditors.Controls;
private void dateEdit1_CloseUp(object sender, CloseUpEventArgs e) {
    DateTime selectedDate = (DateTime)e.Value;
    int currentYear = DateTime.Today.Year;
    if (selectedDate.Year < currentYear)
      e.Value = new DateTime(currentYear, 1, 1);
    else
      if (selectedDate.Year > currentYear)
        e.Value = new DateTime(currentYear, 12, 31);      
}