Example of validating data by using a macro

Example of validating data by using a macro

In some circumstances, you might want to use validation rules that depend on complex conditions, and then take different actions depending on those conditions. For example, because different countries have different rules for their postal codes, a database that stores postal codes for many countries can't rely on a simple validation rule to ensure that a postal code is entered correctly.

You can, however, create a macro that checks which country is entered in the Country control and then checks that the value entered in the PostalCode control has the right characteristics for that country.

First, create a macro that displays different messages depending on the value of the Country control and the length of the entry in the PostalCode control.

Validate data by using a macro

Then, open the form that contains the controls in Design view, and set the BeforeUpdate event property of the form to the name of the macro. You use the form property rather than the control property because the validation involves two different controls on the form.

Now when you use the form to add a new supplier, Microsoft Access runs the validation macro after you finish entering the new record, but before it saves the record in the Suppliers table. If either condition in the macro is met, Access displays the appropriate message and doesn't save the record in the Suppliers table.