You are on page 1of 16

Create a validation rule to validate data in a field

This section explains how to add validation rules to a database. Validation rules restrict
what users can enter in a given field, and also help ensure that your

Understand validation rules

A validation rule limits or controls what users can enter in a table field or a control (such
as a text box) on a form. Microsoft Office Access 2007 provides a number of ways to
validate data, and you often use several of those techniques to define a validation rule.
You can think of validation rules as a set of layers — you can use some or all of the layers
when you need to ensure that your users enter data properly.

 Data types Data types typically provide the first layer of validation. When you
design a database table, you define a data type for each field in the table, and that
data type restricts what users can enter. For example, a Date/Time field accepts only
dates and times, a Currency field accepts only monetary data, and so on.
 Field sizes Field sizes provide another layer of validation. For example, if you
create a field that stores first names, you can set it to accept a maximum of 20
characters. Doing so can prevent a malicious user from pasting in large amounts of
gibberish text into the field, or it can prevent an inexperienced user from mistakenly
entering a first and last name in a field designed only to hold a first name.
 Table properties Table properties provide very specific types of validation. For
example, you can set the Required property to Yes and, as a result, force users to
enter a value in a field.

You can also use the Validation Rule property to require specific values, and
the Validation Text property to alert your users to any mistakes. For example, entering
a rule such as >100 And <1000 in the Validation Rule property forces users to enter
values between 100 and 1,000. A rule such as [EndDate]>=[StartDate]forces users to
enter an ending date that occurs on or after a starting date. Entering text such as "Enter
values between 100 and 1,000" or "Enter an ending date on or after the start date" in
the Validation Text property tells users when they have made a mistake and how to fix
the error.

For the steps needed to add a validation rule to a table field, see the section Validate
data during entry in table fields, later in this article.

 Input masks You can use an input mask to validate data by forcing users to
enter values in a specific way. For example, an input mask can force users to enter
dates in a European format, such as 2007.04.14.

1
You can use some or all of those techniques to validate your data. Some of those features,
such as data types, become part of your database by default, but you can use other
techniques, such as field properties, validation rules, and input masks, at your
discretion.

This article explains how to use the Validation Text and Validation Rule properties
in table fields, queries, and form controls. A complete discussion of other validation tools,
such as data types, field sizes, and input masks, is beyond the scope of this article.

Types of validation rules

You can create two basic types of validation rules:

 Field validation rules Use a field validation rule to check the value that you
enter in a field when you leave the field. For example, suppose you have a Date
field, and you enter >=#01/01/2007# in the Validation Rule property of that
field. Your rule now requires users to enter dates on or after January 1, 2007. If
you enter a date earlier than 2007 and then try to place the focus on another field,
Access prevents you from leaving the current field until you fix the problem.
 Record (or table) validation rules Use a record validation rule to control
when you can save a record (a row in a table). Unlike field validation rules, record
validation rules refer to other fields in the same table. You create record
validation rules when you need to check the values in one field against the values
in another. For example, suppose your business requires you to ship products
within 30 days and, if you don't ship within that time, you must refund part of the
purchase price to your customer. You can define a record validation rule such
as [RequiredDate]<=[OrderDate]+30 to ensure that someone doesn't enter a
ship date (the value in the RequiredDate field) too far into the future.

Where you can use validation rules

You can define validation rules for tables and for controls on forms. When you define
rules for tables, those rules apply when you import data. To add validation rules to a
table, you open the table in Design view and set various table properties. To add
validation rules to a form, you open the form in Design view and add rules to the
properties of individual controls.

The steps in the section Validate data during entry in table fields explain how to add
validation rules to the properties in table fields. The steps in the section Validate data
during entry in forms, later in this article, explain how to add rules to the properties in
individual controls.

2
What you can put in a validation rule

Your validation rules can contain expressions — functions that return a single value.
You can use expressions to perform calculations, manipulate characters, or test data.
When you create validation rules, you use expressions primarily to test data. For
example, an expression can check for one of a series of values, such as "Tokyo" Or
"Moscow" Or "Paris" Or "Helsinki". Expressions can also perform mathematical
operations. For example, the expression <100 forces users to enter values less than 100.
The expression ([OrderDate] - [ShipDate]) calculates the number of days that elapsed
between the time an order was placed and the time it shipped.

A discussion of expressions and functions is beyond the scope of this article. For more
information about expressions, see the article Create an expression. For more
information about functions, see the articles on Microsoft Office Online.

For examples of ways you can use expressions to validate data, see the section Validate
data in a record.

The steps in the following sections explain how to validate data for tables, forms,
queries, and import operations.

Validate data during entry in table fields

The steps in this section explain how to create field-level and record-level validation
rules, and how to test existing data against a new validation rule.

You can enter validation rules for all data types except for the AutoNumber, OLE Object,
and Attachment data types, and for Number fields set to ReplicationID.

Validate data in a field

In the Navigation Pane, right-click the table that you want to change, and then click
Design View.

In the Field Name column, select the field that you want to change.

In the lower section of the table designer, on the General tab, select the Validation Rule
property box, and then enter your validation rule.

-or-

Click On the Data tab of the property sheet, click next to start the Expression Builder
and create your expression.

Enter a rule that applies only to the field. For example, you can enter >0 to force users to
enter positive values.

3
Keep in mind that a validation rule for a field does not reference other fields in the table.
If the rule does reference other fields, you are creating record-level validation.

Select the Validation Text property box and enter a validation message.

The message you enter depends on your validation rule. Keep the message short and try
to explain where the user is going wrong. To continue the example from the previous
step, you could use Enter only positive numbers as the validation text.

Save your work.

Validate data in a record

Repeat steps in the previous section to open a table in Design view.

On the General tab, enter a record-level rule in the Validation Rule property box.

-or-

Click next to start the Expression Builder and create your expression.

A record-level validation rule references more than one table field. For example, a rule
such as [RequiredDate]<=[OrderDate]+30 references two table fields, RequiredDate and
OrderDate, and it ensures that users enter ship dates that occur no later than 30 days
after an order is entered. For more examples of record-level validation, see the section
Validation reference.

Save your changes.

Test your validation rules

Open the table that contains your validation rule in Design View.

On the Design tab, in the Tools group, click Test Validation Rules.

Click Yes to close the alert message and start the test.

If prompted to save your table, Click Yes.

You might see a variety of other alert messages as you proceed. Read the instructions
in each message, and then click Yes or No, as appropriate, to complete or stop
the testing.

4
Test validation rules by using a query

NOTE You can also test your validation rule by writing a query that test for records
that do not conform to your validation rule. The results of such a query show you exactly
which records fail to meet your validation requirements. For example, if you set
the Required property to Yes or Is Not Null, you test for fields that are null.

1. On the Create tab, in the Other group, click Query Design.

Access opens a new query in Design view, and displays the Show Table dialog box.

2. In the Show Table dialog box, select the table or tables that you want to use in
your query, click Add to add them to the query, and then click Close.

The selected tables appear as windows in the upper section of the query designer.

3. In each table, double-click the fields that you want to include in your query.

-or-

Drag the fields from the table and drop them on a blank cell in the Field row in the
lower section of the design grid.

Make sure that you add the field that contains your validation rule.

4. In the Criteria cell of the field that contains your validation rule, enter the
opposite of that rule.

For example, if you use BETWEEN 100 AND 1000, enter <100 OR >1000.

5. On the Design tab, in the Results group, click Run.

Validate data during entry in forms

The easiest and fastest way to apply a validation rule to a form is to first add the rule to
the underlying table field, and then use the automated form-creation tools that Access
provides to create a form. For example, on the Create tab, in the Forms group, you can
choose to have Access create a simple form, a split form, a multiple-item form, and more.
When you use one of those tools, the controls on the form inherit the underlying table
properties, including any validation rules and validation text.

5
You can also apply a validation rule to a form control by opening the form in Design view
and adding a rule to the Validation Rule property and message text to the Validation
Text property of the control. You can add validation rules to some, but not all, form
controls. The easiest way to determine if you can add a validation rule to a control is to
open the form in Design view and follow the steps in this section.

Remember that a control can have a different validation rule than the table field to
which the control is bound. When a conflict develops between validation rules, the rule
defined for the table field takes precedence. Also, remember that rules in controls and
table fields can cancel each other out and thus prevent you from entering any data at all.
For example, suppose you apply the following rule to a date field in a table:

<#01/01/2007#

But you then apply this rule to the form control bound to the table field:

>=#01/01/2007#

The table field now requires values earlier than the year 2007, but the form control
forces you to enter dates after that year, thus preventing you from entering any data at
all. If you try to enter data under those conditions, Access tells you to enter dates before
and after those specified by the conflicting validation rules, and you find yourself caught
in an endless loop.

The following steps explain how to add validation rules to controls, and how to lock
controls and thus prevent users from altering data.

Create a validation rule

1. In the Navigation Pane, right-click the form that you want to change, and then
click Design View.
2. Right-click the control that you want to change, and then click Properties to open
the property sheet for the control.
3. Click the All tab, and then enter your validation rule in the Validation
Rule property box.

-or-

Click next to start the Expression Builder and create an expression.

4. Enter a message in the Validation Text property box.


5. Save your changes.

6
Lock a control

1. Follow steps 1-2 in the previous section to open the property sheet for the control
that you want to lock.
2. Click the All tab, locate the Enabled and Locked property boxes, and then do
one of the following:
 To disable the control (make the control appear dimmed and unable to
receive focus), set the Enabled property to No.
 To make the data in the control readable, but not allow users to change the
data, set the Locked property to Yes. If you set the Enabled property
to No and the Locked property to Yes, the control won't appear dimmed,
but it won't be able to receive focus.

7
A little more on validation rules…

Validation rule examples

The following table provides examples of field-level and record-level validation rules,
plus explanatory validation text. You can adapt these examples to fit your content.

VALIDATION RULE VALIDATION TEXT


<>0 Enter a nonzero value.
>=0 Value must be zero or greater.

-or-

You must enter a positive number.


0 or >100 Value must be either 0 or greater than 100.
BETWEEN 0 AND 1 Enter a value with a percent sign. (For use
with a field that stores number values as
percentages).
<#01/01/2007# Enter a date before 2007.
>=#01/01/2007# AND <#01/01/2008# Date must occur in 2007.
<Date() Birth date cannot be in the future.
StrComp(UCase([LastName]), Data in a field named LastName must be
[LastName],0) = 0 uppercase.
>=Int(Now()) Enter today's date.
M Or F Enter M for male or F for female.
LIKE "[A-Z]*@[A-Z].com" OR "[A-Z]*@[A- Enter a valid .com, .net, or .org e-mail
Z].net" OR "[A-Z]*@[A-Z].org" address.
[RequiredDate]<=[OrderDate]+30 Enter a required date that occurs no more
than 30 days after the order date.
[EndDate]>=[StartDate] Enter an ending date on or after the start
date.

8
Syntax for common validation rules

The expressions in your validation rules don't use any special syntax. The information in
this section explains the syntax for some of the more common types of validation rules.
As you proceed, remember that expressions and functions can be very complex, and a
comprehensive discussion is beyond the scope of this article.

For more information about expressions, see the article Create an expression. For more
information about functions, see the article Functions (arranged by category).

Keep these rules in mind as you create expressions:

Surround the names of table fields with square brackets, like so:
[RequiredDate]<=[OrderDate]+30.

Surround dates with pound signs (#), like so: <#01/01/2007#

Surround text values with double quotation marks, like so: IN


("Tokyo","Paris","Moscow"). Also, note that you separate items with commas, and you
place lists inside parentheses.

In addition to those rules, the following table shows the common arithmetic operators
and provides examples of how you can use them.

OPERATOR FUNCTION EXAMPLE

NOT Tests for converse values. Use before any comparison operator except
IS NOT NULL. NOT > 10 (the same as<=10).

IN Tests for values equal to existing members in a list. Comparison


value must be a comma-separated list enclosed in parentheses.IN
("Tokyo","Paris","Moscow")

BETWEEN Tests for a range of values. You must use two comparison values —
low and high — and you must separate those values with the AND
separator. BETWEEN 100 AND 1000(the same as >=100 AND
<=1000)

LIKE Matches pattern strings in Text and Memo fields. LIKE "Geo*"

IS NOT NULL Forces users to enter values in the field. This is the same as setting
the Required field property to Yes. However, when you enable the
Required property and a user fails to enter a value, Access displays a
somewhat unfriendly error message. Typically, your database is
easier to use if you use IS NOT NULL and enter a friendly message
in the Validation Text property. IS NOT NULL

9
AND Specifies that all the data that you enter must be true or fall within
limits that you specify. >= #01/01/2007# AND <=#03/06/2008#

NOTE You can also useAND to combine validation rules. For example: NOT "UK" AND
LIKE "U*".

OR Specifies that one or more pieces of data can be true.


January OR February

< Less than.

<= Less than or equal to.

> Greater than.

>= Greater than or equal to.

= Equal to.

<> Not equal to.

Validation Rules for fields

When you select a field in table design, you see its Validation Rule property in the lower
pane.

This rule is applied when you enter data into the field. You cannot tab to the next field
until you enter something that satisfies the rule, or undo your entry.

Examples:

To do this ... Validation Rule for Fields Explanation

Accept letters (a - z) only Is Null OR Not Like "*[!a-z]*" Any character outside the
range A to Z is rejected. (Case insensitive.)

Accept digits (0 - 9) only Is Null OR Not Like "*[!0-9]*" Any character outside the
range 0 to 9 is rejected. (Decimal point and negative sign rejected.)

Letters and spaces only Is Null Or Not Like "*[!a-z OR "" ""]*" Punctuation and digits
rejected.

Digits and letters only Is Null OR Not Like "*[!((a-z) or (0-9))]*" Accepts A to Z
and 0 to 9, but no punctuation or other characters.

10
Exactly 8 characters Is Null OR Like "????????" The question mark stands for one
character.

Exactly 4 digits Is Null OR Between 1000 And 9999 For Number fields.

Is Null OR Like "####" For Text fields.

Positive numbers only Is Null OR >= 0 Remove the "=" if zero is not allowed either.

No more than 100% Is Null OR Between -1 And 1 100% is 1. Use 0 instead of -1 if


negative percentages are not allowed.

Not a future date Is Null OR <= Date()

Email address Is Null OR ((Like "*?@?*.?*") AND (Not Like "*[ ,;]*"))
Requires at least one character, @, at least one character, dot,
at least one character. Space, comma, and semicolon are not
permitted.

You must fill in Field1 Not Null Same as setting the field's Required property, but
lets you create a custom message (in the Validation Text
property.)

Limit to specific choices Is Null OR "M" Or "F" It is better to use a lookup table for
the list, but this may be useful for simple choices such as
Male/Female.

Is Null OR IN (1, 2, 4, 8) The IN operator may be simpler than several ORs.

Yes/No/Null field Is Null OR 0 or -1 The Yes/No field in Access does not support
Null as other databases do. To simulate a real Yes/No/Null
data type, use a Number field (size Integer) with this rule.
(Access uses 0 for False, and -1 for True.)

Validation Rules for tables

In table design, open the Properties box and you see another Validation Rule. This is the
rule for the table.

The rule is applied after all fields have been entered, just before the record is saved. Use
this rule to compare values across different fields, or to delay validation until the last
moment before the record is saved.

11
Examples:

To do this ... Validation Rule for Table Explanation

A booking cannot end before it starts ([StartDate] Is Null) OR ([EndDate] Is Null) OR


([StartDate] <= [EndDate]) The rule is satisfied if either field is left blank;
otherwise StartDate must be before (or the same as) EndDate.

If you fill in Field1, Field2 is required also ([Field1] Is Null) OR ([Field2] Is Not Null)
The rule is satisfied if Field1 is blank; otherwise it is satisfied only if Field2 is
filled in.

You must enter Field1 or Field2, but not both ([Field1] Is Null) XOR ([Field2] Is Null)
XOR is the exclusive OR.

Text validation rule examples

The following validation rule examples apply to text fields.

Example Matches...

Like "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-
A number consisting of 8 digits
9]"

Like "########" A number consisting of 8 digits

Like "????" 4 characters

Like "K*" A text starting with the letter K or k

Is Not Null Any value but null/empty

A text staring with the letter K/k, followed by zero or more


Not Null And Like "K*i*e" characters (*), followed by a i/I, followed by zero or more
characters (*), followed by an e. Null/empty is not allowed.

Like "James Joyce" Matches "James Joyce"

Matches an a, followed by any single character, followed by a


Like "a?b?c"
b, followed by any single character, followed by a c

A very basic email validation rule. This matches any


number of characters (including no characters), followed by an
Like "*@*.*" @, followed by any number of characters (uncluding no
characters), followed by a ., followed by any number of
characters (including no characters).

A basic email validation rule. Matches at least two


Like "??*@??*.??*" characters, followed by an @ sign, followed by at least two
characters, followed by a ., followed by at least two characters.

12
Like "bi[nd]" Matches "bin" or "bid"

Matches two characters, followed by an a or a b, followed by


Like "??[ab]*" And Not Like "*[q]*" any number of characters and NONE of the characters can be
a q.

Matches two characters, followed by an a or b, followed by any


Like "??[ab]*" And Not Like "*[!qab]*" number of characters and ALL of the characters must be q, a
or b.

Matches two characters, followed by a digit, followed by any


Like "??#*" And Not Like "*[!0-9]*" number of characters and ALL of the characters must be
numbers.

More advanced email validation. Matches the pattern


Like "?*@?*.??*" And Not Like "*[!a-
"?*@?*.??" if ALL characters are part of the the [a-
z@=.^_$%!#&'`{|}*?~/-]*"
z@=.^_$%!#&'`{|}*?~/-] character collection.

Not Like "*[!a-z]*" Letters only

Not Like "*[!a-z ]*" Letters and spaces only

Not Like "*[!0-9a-z]*" Letters and numbers only

Not Like "*[!0-9a-z -]*" Letters, numbers, spaces and hyphens (-) only

"Jack" Or "John" Or "Marc" Jack, John or Marc

Number validation rule examples

The following validation rule examples apply to Number fields.

Example Matches...
>0 Positive numbers only, excluding 0

>= 0 Positive numbers only, including 0

>= 0 And <= 100 Between 0 and 100, including 0 and 100

Between 0 And 100 Between 0 and 100, including 0 and 100

In(1,2,3,4,5) 1,2,3,4 or 5

1 Or 2 Or 3 Or 4 Or 5 1,2,3,4 or 5

13
Date validation rule examples

The following validation rule examples apply to dates. Note that the way dates are
written depends on your locale. The examples below use a European date format (dd-
mm-yyyy).

Example Matches...
>#28/2/1990# Dates after 28 februari 1990

Dates between 28 februari and 5 march


Between #28/2/1990# And #5/3/1990#
1980

Dates between 28 februari and 5 march


>= #28/2/1980# And <= #5/3/1990#
1980

> #28/2/1990 13:45# Date/Time after 28 februari 1990 13:45

> Date() Dates after today’s date

> Now() Date/Time after the current Date/Time

EXPRESSIONS

Create an expression

This article explains how to create and use expressions in Microsoft Access. You use
expressions to perform many of the same tasks for which you use formulas in Microsoft
Excel. This article shows you where to use expressions, depending on the specific task
that you want to accomplish, and it shows you how to manually create expressions and
how to create expressions by using the Expression Builder tool.

Overview of expressions
An expression is a combination of some or all of the following: built-in or user-
defined functions, identifiers, operators, and constants. Each expression evaluates to a
single value.

or example, the following expression contains all four of these elements:


=Sum([Purchase Price])*0.08
In this example, Sum() is a built-in function, [Purchase Price] is an identifier, * is a
mathematical operator, and 0.08 is a constant. This expression might be used in a text
box in a form footer or report footer to calculate sales tax for a group of items.
Expressions can be much more complex or much simpler than this example. For example,
this Boolean expression consists of just an operator and a constant: >0
14
This expression returns True when it is compared to a number that is greater than 0, and
returns False when it is compared to a number that is less than or equal to 0. You can
use this expression in the Validation Rule property of a control or table field to ensure
that only positive values are entered.
The following table shows more examples of expressions:
EXPRESSION PURPOSE
=[RequiredDate]-[ShippedDate] By subtracting one identifier
from another, you can
calculate the difference
between the values in two text
box controls on a report.
Date() By using the Date function,
you can set the default value
for a field in a table to the
current date.
ExtendedPrice: By using functions,
CCur([Order Details].UnitPrice*[Quantity]* identifiers, and constants, you
(1-[Discount])/100)*100 can create a calculated field
named “ExtendedPrice” in a
query. The CCur function
converts the result of the
calculation to the Currency
data type.
Between #1/1/2005# And #12/31/2005# By using date constants
(enclosed in pound signs to
signify that Access should
treat them as dates), you can
enter criteria for a Date/Time
field in a query.
=[Orders Subform].Form!OrderSubtotal By using the complete
identifier for
the OrderSubtotal control on
the Orders subform, you can
display its value on the main
form.

15
=Format(Date(),"mmmm d, By using the Format function,
yyyy") you can format a date in a
variety of ways. “mmmm”
specifies that the month name
is spelled out in full; “d”
specifies that the day is
displayed with either 1 or 2
digits, and “yyyy” specifies
that the year is displayed with
4 digits. For example, on
2/8/2006 this expression would
return “February 8, 2006”.
As shown in the preceding table, expressions are used in many places to perform
calculations, manipulate characters, or test data. Tables, queries, forms, reports, and
macros all have properties that accept an expression. Some examples include:
 The Control Source and Default Value properties for a control
 The Validation Rule property for a table field
 The Field or Criteria row of a query
 A macro or Microsoft Visual Basic for Applications (VBA) module
The following sections describe the most common ways in which you can use expressions.

Create a calculated control on a form or report


When you use an expression as the data source for a control, the control is referred to as a
calculated control. For example, suppose that you have an order form that displays
multiple order records, and you want to create a subtotal in the form footer that sums all
of the line items on the form.

16

You might also like