Translate to:

Online Delphi Training

Learn LIVE
From The Comfort Of Your Home
Start Immediately!

+1 (678) 921-0644

Using Constraints To Validate Data In Delphi

One of the many things that I love about Delphi is the fact that it is a RAD (Rapid Application Development) environment. So much is prebuilt in its IDE that very little code is required to achieve certain functionalities that would require extensive coding in other languages.

Delphi is extremely powerful and versatile, especially when it comes to creating database applications. It comes ready with many components that facilitate and speed up database development.

One important aspect of database development is the validation of data. The data is validated to match the database before any data is sent to the server for posting. This ensures the compatibility of data, and reduces network traffic.

Without validation, invalid data could be sent to the server which would then reject the data and send it back to the client with a database error. When you use data validation, data entry inconsistencies or errors are trapped on the client side long before they get to the server.

This example will show you how to create data constraints in Delphi for validating data entry. On a side note, in a multi-tier application, these data constraints can be setup on the application server (middle tier) instead of the client, and the server would then pass them to the client.

Create a new application and drop a panel on the form. On the panel, drop a DBNavigator and a BitBtn. Set the Kind property of the BitBtn to "bkClose." Drop a DBGrid on the form and set its Align property to "alClient." Next, drop a ClientDataSet (name it tblEmp) and a DataSource (name it dsEmp) onto the form. Set the DataSet property of dsEmp to tblEmp. And set the DataSource property of the DBNavigator and of the DBGrid to dsEmp.

In this example, I will use "C:\Program Files\Common Files\Borland Shared\Data\employee.cds" in the FileName property of tblEmp. When you install Delphi, these data files are also installed for demo purposes. They may be located elsewhere on your system.

Double-click on tblEmp and add all available fields to the Fields Editor dialog:

We will now add the following constraints:

  1. The employee number must be greater than zero.
  2. The last name is required.
  3. The salary must be a positive number and cannot exceed $150,000.

While we are at it, we will also modify the display and edit formats, and set a default value for the salary. The formats are for display purposes (experiment with them to see the results). The default value is not a constraint. It is merely a suggestion for the user.

Click on the EmpNo field in the Fields Editor. Look for its CustomConstraint property in the Object Inspector and enter the following expression: "x > 0" (without the quotes). Above it, you will find the ConstraintErrorMessage property. Type in the following error message to be displayed to the user: "The employee number must be greater than zero" (no quotes).

Similarly, click on the LastName field in the Fields Editor. Set its CustomConstraint property to: x <> '' and its ConstraintErrorMessage property to: The last name is required.

To setup our third constraint, click on the Salary field in the Fields Editor. Set its CustomConstraint property to: x > 0 and x < 150000 and its ConstraintErrorMessage property to: The employee salary must be a positive number that is less than 150000.

To setup the display formats and the default expression, set the following Salary properties as below:

DefaultExpression: 30000 (When you insert a new record, this value will automatically be entered in the Salary field as the default value. You can change it, of course).
DisplayFormat: $#,###.00 (This will display the number 90143.12, for example, as $90,143.12)
EditFormat: ####.00 (When you click in the Salary field to edit its value, it will remove the formatting. The formatted number $90,143.12 will be presented as 90143.12. This will facilitate data entry.)

This completes the main part of our application, and we have not written a single line of code! We will now add some code to help us with some details.

Add the following code to the Form's OnCreate Event:

tblEmp.Open; // This will open the table when the form gets created.

Add the following code to the Form's OnClose Event:

tblEmp.Close; // This will close the table when the form is closed.

Next, add the following code to the Form's OnCloseQuery Event:

if MessageDlg('Are you sure you want to close this application?',
          mtConfirmation, [mbYes,mbCancel],0) <> mrYes then CanClose := False
else if tblEmp.State in [dsEdit,dsInsert] then
               if MessageDlg('Do you wish to save the changes?', mtConfirmation,
                    [mbYes,mbNo],0) = mrYes then tblEmp.Post;

This last bit of code will intercept an attempt to exit the application and verify that this was intended. If confirmed, it will check the state of the tblEmp table. If data is being inserted or updated, it will prompt the user to find out if the changes should be saved.

Now, compile, save and run the application:

Notice the formatted salary column above. If you double-click in the salary field, you will enter edit mode and the formatting will disappear (EditFormat property):

Click on the INSERT button, enter a negative number in the EmpNo and click away from it. You will get the following error (our first constraint in action):

Also notice the default value of $30,000.00 entered automatically in the Salary field (DefaultExpression property).

Get rid of the negative sign, and click away from the record. You will get the following error (our second constraint in action):

Enter a last name. Now, change the salary value to a negative number or to 150000 or more, and click away from the record. You will get the following error (our third constraint in action):

Change the value to a valid number, but remain in edit mode in the salary field. Now, click on the Close button. You will get prompted to confirm your intention to close the application:

If you click Cancel, you will be returned to the application. If you click on Yes, you will get another prompt about saving the data:

If you click on No, the changes will be discarded before the application is closed. If you click on Yes, your changes will be saved before the application is closed.

Do you have any comments about this topic?

Click on: Post Comments/Questions

To download the project click on: Delphi Tip Download

©2005-2006 Business-IQ