Validating DetailsView field values during Insert and Update

If you want to perform validation on the fields of a DetailsView at run time you can hook into the ItemInserting and ItemUpdating events as shown below. By Setting e.Cancel to true, it is possible to abort the insert/update action, and thus force the user to return to the form.

/// <summary>
/// Check if the chosen date represents a valid Date, and check the lower and upper bounds
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void DetailsViewHR_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
    DateTime lowerbound = new DateTime(1899,1,1);
    DateTime upperbound = DateTime.Now.Date;
    DateTime checkDate;
 
    // Check if the data is parsable as a valid datetime
    if (!DateTime.TryParse(e.Values["hrGebDat"].ToString(), out checkDate))
    {
        e.Cancel = true;
        return;
    }
     
    // Check if the range is acceptable
    if (checkDate < lowerbound || checkDate > upperbound)
    {
        e.Cancel = true; // abort insert
    }
}

The ItemUpdating EventArgs do not contain e.Values for the fields, but instead offer e.OldValues and e.NewValues to enable you to compare the previous and new content of the field. The same procedure of checking for a valid DateTime and the upper/lower bound applied to the update event can be archieved as:

protected void DetailsViewPerson_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
    DateTime lowerbound = new DateTime(1899, 1, 1);
    DateTime upperbound = DateTime.Now.Date;
    DateTime checkDate;
 
    // Check if the data is parsable as a valid datetime
    if (!DateTime.TryParse(e.NewValues["hrGebDat"].ToString(), out checkDate))
    {
        e.Cancel = true;
        return;
    }
 
    // Check if the range is acceptable
    if (checkDate < lowerbound || checkDate > upperbound)
    {
        e.Cancel = true; // abort insert
    }
}