0% found this document useful (0 votes)
2K views15 pages

Validation Rule

1. The document describes how to create field validation rules in Microsoft Access to block invalid data from being entered. 2. It provides steps for setting up a basic validation rule to prevent negative or zero numbers from being entered in a numeric field. 3. Various validation expressions are presented for validating different data types, such as using comparison operators to check if a number is within a certain range or if a date occurs before or after a given date value formatted with universal date syntax.

Uploaded by

Eman Moh'd
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views15 pages

Validation Rule

1. The document describes how to create field validation rules in Microsoft Access to block invalid data from being entered. 2. It provides steps for setting up a basic validation rule to prevent negative or zero numbers from being entered in a numeric field. 3. Various validation expressions are presented for validating different data types, such as using comparison operators to check if a number is within a certain range or if a date occurs before or after a given date value formatted with universal date syntax.

Uploaded by

Eman Moh'd
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

http://www.aspfree.

com/c/a/MS-SQL-Server/Field-Validation-Rules-for-Blocking-Bad-
Data/2/

http://office.microsoft.com/en-us/access-help/create-a-validation-rule-to-validate-data-in-a-
field-HA010096312.aspx

Field Validation Rules for Blocking Bad Data - Applying a Field Validation Rule
(Page 2 of 4 )

Each field can have a single validation rule. The following set of steps show you how to set one up. You’ll
start out easy, with a validation rule that prevents a numeric field from accepting 0 or any negative number
(and in the following sections you’ll hone your rule-writing abilities so you can tackle other data types).
Here’s how to add your validation rule:
1. In Design view, select the field to which you want to apply the rule.

All data types—except Memo, AutoNumber, and OLE Object—support validation. The validation rule
in this example works with any numeric data type (like Number or Currency). 
2. In the Validation Rule field property, type a validation expression (Figure 4-14).

An expression’s a bit of SQL that performs a check on the data you’ve entered. Access performs its
validation check when you finish entering a piece of data, and try to navigate to another field or
another record. For example, >0 is a validation rule that forces the value in a Number field to be
larger than 0. You’ll learn more validation rules in the following sections.

Figure 4-14.
Here, the Validation Rule property prevents
impossible prices, and the Validation Text
provides an error message.

3. Type some error-message text in the Validation Text field property.

If you enter a value that fails the validation check, then Access rejects the value and displays this
error text in a dialog box. If you don’t supply any text, then Access shows the validation rule for the
field (whatever you entered in step 2), which is more than a little confusing for most mere mortals. 

4. Right-click the tab title, and then choose Datasheet View.

If your table has existing records, Access gives you the option of checking them to make sure they
meet the requirements of your validation rule. You decide whether you want to perform this check,
or skip it altogether.

Once you’re in Datasheet view, you’re ready to try out your validation rule (Figure 4-15).
Figure 4-15.
Here, a validation rule of >0 prevents negative
numbers in the Price field. When you enter a
negative number, Access pops up a message box
with the validation text you defined, as shown
here. Once you click OK, you return to your field,
which remains in edit mode. You can change
the value to a positive number, or press Esc to
cancel the record edit or insertion.

Note: Just because your table has validation rules doesn’t mean the data inside follows these rules. A discrepancy can occur if you
added records before the validation rules came into effect. (You learned about the same potential problem with required fields on page
116.) To avoid these headaches, set up your validation rules before you start adding data.

Field Validation Rules for Blocking Bad Data - Writing a Field Validation Rule
(Page 3 of 4 )

As you can see, it’s easy enough to apply a validation rule to a field. But creating the right validation rule
takes more thought. In order to get the result you want, you need to take your first step into the sometimes
quirky world of SQL.
Although validation’s limited only by your imagination, Access pros turn to a few basic patterns again and
again. The following sections give you some quick and easy starting points for validating different data types.

Note: Access uses your validation rule only if a field contains some content. If you leave it blank, then Access accepts if without any
checks. If this isn’t the behavior you want, then just set the Required property to Yes to make the field mandatory, as described on page
116.

Validating numbers
For numbers, the most common technique’s to check that the value falls in a
certain range. In other words, you want to check that a number’s less than or
greater than another value. Your tools are the comparison signs < and >. Table
4-3 shows some common examples.
Table 4-3.  Expressions for Numbers
Comparison Sample Expression Description

Less than <100 The value must be less than 100.

Greater than >0 The value must be greater than 0.

Not equal to <>42 The value can be anything except


42.
Less than or equal to <=100 The value must be less than or
equal to 100.

Greater than or equal to >=0 The value must be greater than or


equal to 0.

Equal to =42 The value must be 42. (Not much


point in asking anyone to type it in,
is there?)

Between Between 0 and 100 The value must be 0, 100, or


somewhere in between.

Validating dates
As with numbers, date validation usually involves checking to see if the value falls within a specified range.
Here, your challenge is making sure that your date’s in the right format for an expression. If you use the
validation rule >Jan 30, 2007, Access is utterly confused, because it doesn’t realize that the text (Jan 30,
2007) is supposed to represent a date. Similarly, if you try >1/30/07, then Access assumes the numbers on
the right are part of a division calculation.
To solve this problem, use Access universal date syntax, which looks like this:
  #1/30/2007#
A universal date always has the date components in the order month/day/year, and it’s always bracketed by
the # symbol on either side. Using this syntax, you can craft a condition like >#1/30/2007#, which states
that a given date must be larger than (fall after) the date January 30, 2007. January 31, 2007 fits the bill,
but a date in 2006 is out.
The universal date syntax can also include a time component, like this:
  #1/30/2007 5:30PM#

Note: When comparing two dates, Access takes the time information into consideration. The date #1/30/2007# doesn’t include any time
information, so it’s treated as though it occurs on the very first second of the day. As a result, Access considers the date value #1/30/2007
8:00 AM# larger, because it occurs eight hours later. 

Once you’ve learned the universal date syntax, you can use any of the comparison operators you used with numbers. You can also use
these handy functions to get information about the current date and time:
 Date( ) gets the current date (without any time information, so it counts as the first second of the
day).
 Now( ) gets the current instant in time, including the date and time information.

Note: A function’s a built-in code routine that performs some task, like fetching the current date from the computer clock. You’ll learn
about many more date functions, which let you perform advanced tasks like finding the day of the week for a date, on page 229.

Table 4-4 has some examples.


Table 4-4.  Expressions for Dates
Comparison Sample Expression Description

Less than <#1/30/2007# The date occurs before January 30,


2007.

Greater than >#1/30/2007 5:30 PM# The date occurs after January 30,
2007, or on January 30, 2007, after
5:30 p.m.

Less than or equal to <=#1/30/2007# The date occurs before January 30,
2007, or on the first second of
January 30, 2007.

Greater than or equal to >=#1/30/2007# The date occurs on or after Janu-ary


30, 2007.

Greater than the current date >Date( ) The date occurs today or after.

Less than the current date <Date( ) The date occurs yesterday or before.

Greater than the current date (and >Now( ) The date occurs today after the
time) current time, or any day in the
future. 

Less than the current date (and The date occurs today before the
<Now( )
time)  current time, or any day in the past. 

Field Validation Rules for Blocking Bad Data - Validating text


(Page 4 of 4 )

With text, validation lets you verify that a value starts with, ends with, or contains specific characters. You
perform all these tasks with the Like operator, which compares text to a pattern.
This condition forces a field to start with the letter R:
  Like "R*"
The asterisk (*) represents zero or more characters. Thus, the complete expression asks Access to check
that the value starts with R (or r), followed by a series of zero or more characters.
You can use a similar expression to make sure a piece of text ends with specific characters:
  Like "*ed"
This expression allows the values talked, walked, and 34z%($)#ed, but not talking, walkable, or 34z%($)#.
For a slightly less common trick, you can use more than one asterisk. The following expression requires that
the letter a and b  appear (in that order but not necessarily next to each other) somewhere in a text field:
  Like "*a*b*"
Along with the asterisk, the Like operator also supports a few more characters. You can use ? to match a
single character, which is handy if you know how long text should be or where a certain letter should appear.
Here’s the validation rule for an eight-character product code that ends in 0ZB:
  Like "?????0ZB"
The # character plays a similar role, but it represents a number. Thus, the following validation rule defines a
product code that ends in 0ZB and is preceded by five numbers:
  Like "#####0ZB"
And finally, you can restrict any character to certain letters or symbols. The trick’s to put the allowed
characters inside square brackets.
Suppose your company uses an eight-character product code that always begins with A or E. Here’s the
validation rule you need:
  Like "[AE]???????"
Note that the [AE] part represents one character, which can be either A or E. If you wanted to allow A, B, C,
D, you’d write [ABCD] instead, or you’d use the handy shortcut [A-D], which means “allow any character
from A to D, including A and D.”
Here’s one more validation expression, which allows a seven-letter word, and doesn’t allow numbers or
symbols. It works by repeating the [A-Z] code (which allows any letter) seven times.
  Like [A-Z][A-Z][A-Z][A-Z][A-Z][A-Z][A-Z]
As you can see, text validation expressions aren’t always pretty. Not only can they grow to ridiculous sizes,
but there are lots of restrictions they can’t apply. You can’t, for instance, let the length of the text vary
between a minimum and maximum that you set. And you can’t distinguish between capitalized and
lowercase letters.

Note: You can get around many of these limitations using some of the functions that Access provides. On page 228, you’ll learn how to
use functions that can snip out bits of text, test lengths, check
capitalization, and more.

Combining validation conditions


No matter what the data type, you can also combine your conditions in two different ways. Using the And
keyword, you can create a validation rule that enforces two requirements. This trick’s handy, because each
field can have at most a single validation rule.
To use the And keyword, just write two validation rules and put the word And in between. It doesn’t matter
which validation rule’s first. Here’s a validation rule that forces a date to be before today but later than
January 1, 2000:
  <Date() And >#1/1/2000#
You can also use the Or keyword to accept a value if it meets either one of two conditions. Here’s a
validation rule that allows numbers greater than 1000 or less than –1000:
  >1000 Or <-1000
Please check back tomorrow for the conclusion to this article.

Create a validation rule to validate data in a field


Applies to: Microsoft Office Access 2007
Print

This article 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 database users enter the proper types or amounts of data.
What do you want to do?

 Understand validation rules


 Validate data during entry in table fields
 Validate data during entry in forms
 Validate data during import operations
 Validation rule reference

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.
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.
For more information about data types and field sizes, see the article Modify or change the data type set for a field. For more
information about input masks, see the article Create an input mask to enter field or control values in a specific format.

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.
If the syntax for validation rules looks cryptic, the tables in the section What you can put in a validation rule explain the syntax
and provide some example validation rules.
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.

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.
TOP OF PAGE

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


1. In the Navigation Pane, right-click the table that you want to change, and then click Design View.
2. In the Field Name column, select the field that you want to change.
3. 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.
For more information about using the Expression Builder, see the article Create an expression.
Enter a rule that applies only to the field. For example, you can enter >0 to force users to enter positive values. 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.
4. 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.
5. Save your work.
 NOTE    For more examples of field-level validation, see the section Validation reference, later in this article.

Validate data in a record


1. Repeat steps 1-2 in the previous section to open a table in Design view.
2. 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.
For more information about using the Expression Builder, see the article Create an 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.
3. Save your changes.

Test your validation rules


1. Open the table that contains your validation rule in Design View.
2. On the Design tab, in the Tools group, click Test Validation Rules.
3. Click Yes to close the alert message and start the test.
4. If prompted to save your table, Click Yes.
5. 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.

Test validation rules by using a query


 NOTE    You can also test your validation rule by writing a query that tests 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.
TOP OF PAGE

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.
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.


For more information about using the Expression Builder, see the article Create an expression.
4. Enter a message in the Validation Text property box.
5. Save your changes.
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.
TOP OF PAGE

Validate data during import operations


When you add validation rules to a table and you then import data into that table, Access applies your validation rules to the
imported data. The same rule applies when you link to data.
For more information about importing or linking to data, see the following articles:
 Import or link to data in another Access database
 Import or link to data in an Excel workbook
 Import from or link to a SharePoint list
 Import or link to data in a text file
TOP OF PAGE

Validation rule reference


The following tables provide reference information for validation rules, including the syntax that the most common rules use,
links to information about using wildcard characters in your rules, and examples that you can adapt for use with your data.

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 uppercase.


[LastName],0) = 0

>=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-Z].net" OR "[A- Enter a valid .com, .net, or .org e-mail address.
Z]*@[A-Z].org"

[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.

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 NOT > 10 (the same as <=10).
operator except IS NOT NULL.

IN Tests for values equal to existing members in a list. IN ("Tokyo","Paris","Moscow")


Comparison value must be a comma-separated list enclosed
in parentheses.

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

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 IS NOT NULL
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.

AND Specifies that all the data that you enter must be true or fall >= #01/01/2007# AND <=#03/06/2008#
within limits that you specify.
 NOTE    You can also use AND 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.

Using wildcard characters in validation rules


You can use any of the wildcard characters that Access provides in your validation rules. Keep in mind that Access supports
two sets of wildcard characters. Access does so because it supports two standards for Structured Query Language (SQL), the
language used to create and manage databases: ANSI-89 and ANSI-92. Each of those standards uses a different set of
wildcard characters.
By default, all .accdb and .mdb files use the ANSI-89 standard; conversely, Access projects use the ANSI-92 standard. If you
are new to Access, in an Access project, the tables in your database reside on a computer running Microsoft SQL Server, and
the forms, reports and other objects reside on other computers. You can change the ANSI standard for .accdb and .mdb files
to ANSI-92, if you want.
For more information about using wildcard characters and the ANSI standards for SQL, see the article Access wildcard
character reference.

Validatin Rule

Control data entry formats with input masks


Applies to: Microsoft Access 2010, Access 2007
Print

When you have several people entering data in your database, you can define how users must enter data in specific fields to
help maintain consistency and to make your database easier to manage. For example, you can set an input mask for a form
so that users can only enter telephone numbers in the Swedish format or addresses in the French format. You can set a
specific format for the input mask, and select another format so that the same data is displayed differently.
This article will help you learn more about input masks, when to use them, and how to create them.
What do you want to do?

 Learn more about input masks


 Know more about characters that define input masks
 Add or create input masks
 Consider the usage before applying an input mask
 Examples of input masks

Learn more about input masks


Let's start with where and when you might want to use input masks. You can add input masks to table fields, queries, and to
form and report controls.
For example, you can add an input mask to a Date/Time field in a table, or to a text box control on a form that you bind to a
Date/Time field. You can also add input masks to form controls, such as text boxes, that you bind to table fields that are set
to those data types. If you are unfamiliar with data types, see the article Introduction to data types and field properties.
Input masks provide a set format for data entry in a field by using characters and symbols. When you apply an input mask to
a field, anyone who inputs data in that field must follow the specific pattern defined by the input mask. For example, if the
database user enters a phone number without the area code, in this particular mask, (___) 555-0187 xt. ___ the user will be
unable to save the data until the area code data is added. The exact behavior depends on the how the database designer sets
up the input mask.
Input masks provide a large amount of data validation and prevent users from entering invalid data (such as a phone number
in a date field). Input masks can also help ensure that users enter data in a consistent way. That consistency can make data
easier to find and make it easier to maintain your database.
Remember that you define input masks to control the format in which data is entered in the database but you can apply
another format to the same data to change how the data is displayed. For example, your input mask can define dates to be
entered in a format such as YYYY.MM.DD, but have the date appear as DD-MMM-YYYY.

The three parts of an input mask


Input masks are made up one mandatory part and two optional parts, and each part is separated by a semicolon. The
purpose of each part is as follows:
 The first part is mandatory. It includes the mask characters or string (series of characters) along with placeholders
and literal data such as, parentheses, periods, and hypens.
 The second part is optional and refers to the embedded mask characters and how they are stored within the field.
If the second part is set to 0, the characters are stored with the data, and if it is set to 1, the characters are only displayed and
not stored. Setting the second part to 1 can save database storage space.
 The third part of the input mask is also optional and indicates a single character or space that is used as a
placeholder. By default, Access uses the underscore (_). If you want to use another character, enter it in the third part of your
mask.
For example, this is an input mask for a telephone numbers in the U.S. format: (999) 000-000;0;-:
 The mask uses two placeholder characters, 9 and 0. The 9 indicates an optional digit (which makes it optional to
enter an area code), and each 0 indicates a mandatory digit.
 The 0 in the second part of the input mask indicates that the mask characters will be stored along with the data.
 The third part of the input mask specifies that a hyphen (-) instead of the underscore (_) is to be used as the
placeholder character.
TOP OF PAGE

Know more about characters that define input


masks
The following table lists the placeholder and literal characters for an input mask and explains how it controls data entry:

CHARACTE EXPLANATION
R

0 User must enter a digit (0 to 9).

9 User can enter a digit (0 to 9).

# User can enter a digit, space, plus or minus sign. If skipped, Access enters a blank space.

L User must enter a letter.

? User can enter a letter.

A User must enter a letter or a digit.

a User can enter a letter or a digit.

& User must enter either a character or a space.

C User can enter characters or spaces.

.,:;-/ Decimal and thousands placeholders, date and time separators. The character you select depends on your
Microsoft Windows regional settings.

> Coverts all characters that follow to uppercase.

< Converts all characters that follow to lowercase.

! Causes the input mask to fill from left to right instead of from right to left.

\ Characters immediately following will be displayed literally.

"" Characters enclosed in double quotation marks will be displayed literally.

TOP OF PAGE

Add or create input masks


You can either quickly add input masks by using the Input Mask Wizard, or specify masks manually by typing custom masks
to the Input Mask field property setting.

Add input masks by using the Input Mask Wizard


This section describes how you can add a predefined input mask to a table field, a query, or a form or report control by using
the Input Mask Wizard.

 Add an input mask to a table field


 Add an input mask to a query
 Add an input mask to a form or report control
Add an input mask to a table field
You can use input masks with fields that are set to the Text, Number (except ReplicationID), Currency, and Date/Time data
types.
 NOTE    If you use an input mask for a Date/Time field, the Date Picker control becomes unavailable for that field.

1. In the Navigation Pane, right-click the table and click Design View on the shortcut menu.
2. Click the field where you want to add the input mask.
3. Under Field Properties, on the General tab, click the Input Mask property box.

4. Click the Build button to start the Input Mask Wizard.


5. In the Input Mask list, select the type of mask that you want to add.

6. Click Try it and enter data to test how the mask displays.
7. To keep the input mask without any changes, click Next.
8. Select an option for how you want the data to be stored.
9. Click Finish and save your changes.
Top of section

Add an input mask to a query


1. In the Navigation Pane, right-click the query that you want to change and click Design View on the shortcut
menu.
2. In the query design grid, place the pointer in the column for the field you want to change.
You can place the cursor in any row for that field.
3. Press F4 to open the property sheet for the field.
4. Under Field Properties, on the General tab, click the Input Mask property box.

5. Click the Build button to start the Input Mask Wizard, and then follow the instructions in the wizard.
Top of section

Add an input mask to a form or report control


1. In the Navigation Pane, right-click the form or report that you want to change and click Design View on the
shortcut menu.
2. Right-click the control that you want to change, and then click Properties on the shortcut menu.
3. On the All tab, click the Input Mask property box.

4. Click theBuild button to start the Input Mask Wizard, and then follow the instructions in the wizard.
Top of section

Create custom input masks


While the Input Mask Wizard provides input masks for most common formatting needs, you may sometimes want to
customize input masks to better suit your needs. Input masks can be customized by either changing the predefined masks
from the Input Mask Wizard or by manually changing the Input Mask property for a field where you want the mask applied.

Customizing input masks from the Input Mask Wizard


1. Open the object in Design View, and click the field where you want to add the custom input mask.

2. Click the Build to start the Input Mask Wizard.


3. Click Edit List.
The Customize Input Mask Wizard dialog box appears.

4. Enter a new description in the Description text box using characters and placeholders from the table.
5. Click the Mask Type down arrow and select a suitable mask type.
6. Click Close. The new input mask displays in the list.

Customize input masks from the field property setting


1. In the Navigation Pane, right-click the object and click Design View on the shortcut menu.
2. Click the field where you want to create the custom input mask.
3. In the Field Properties area, click the Input Mask text box, and then type your custom mask.
4. Press CTRL+S to save your changes.
For more information about how to define an input mask, click the Input Mask property box, and then press F1. You must
manually type the input mask definition for Number and Currency fields.
TOP OF PAGE

Consider the usage before applying an input


mask
It is usually a good idea to consider how data entry needs might change as your database grows and here are several general
questions that you can start with:
 Will the mask prevent users from entering necessary data? For example, will users ever need to enter phone in a
format from another region?
 Does the mask interfere with the display format settings? For example, switch to Design view and, in the Format
property of the field that contains your input mask, type this format string: (&&&) @@@-@@@@. When you view the field
in Datasheet view, you see something like this: (425() 5) 55--1212.
 Do you plan on using the Date Picker on a Date/Time field? If you do, then you cannot apply an input mask to that
field.
TOP OF PAGE

Examples of input masks


The examples in the following table demonstrate some ways that you can use input masks.

THIS INPUT MASK PROVIDES THIS TYPE NOTES


OF VALUE

(000) 000-0000 (206) 555-0199 In this case, you must must enter an area code because that
section of the mask (000, enclosed in parentheses) uses the 0
placeholder.

(999) 000-0000! (206) 555-0199 In this case, the area code section uses the 9 placeholder, so
( ) 555-0199 area codes are optional. Also, the exclamation point (!) causes the
mask to fill in from left to right.

(000) AAA-AAAA (206) 555-TELE Allows you to substitute the last four digits of a U.S. style phone
number with letters. Note the use of the 0 placeholder in the area
code section, which makes the area code mandatory.

#999 -20 Any positive or negative number, no more than four characters,
2000 and with no thousands separator or decimal places.

>L????L?000L0 GREENGR339M3 A combination of mandatory (L) and optional (?) letters and
MAY R 452B7 mandatory numbers (0). The greater-than sign forces users to
enter all letters in uppercase. To use an input mask of this type,
you must set the data type for the table field to Text or Memo.

00000-9999 98115- A mandatory postal code and an optional plus-four section.


98115-3007

>L<?????????????? Maria A first or last name with the first letter automatically capitalized.
Pierre
ISBN 0-&&&&&&&&&-0 ISBN 1-55615-507-7 A book number with the literal text, mandatory first and last digits,
and any combination of letters and characters between those
digits.

>LL00000-0000 DB51392-0493 A combination of mandatory letters and characters, all uppercase.


Use this type of input mask, for example, to help users enter part
numbers or other forms of inventory correctly.

An input mask is a special pattern that controls what the user can type into a
MaskedInput dialog or edit field control at run time. The mask can be any
combination of regular text characters, called "literals," and special characters, called
"placeholders." Each placeholder represents one "place" in the edit field where the
user can type a character. Different placeholders allow different kinds of characters to
be typed in their "place" by the user. For example, the # placeholder only allows a
digit between 0 and 9 to be typed in its place, and the ? placeholder only allows a
letter between a and z.
Note: The placeholder characters you use in the input mask determine what the user will be
allowed to type into the edit field.

You can use literals to include "normal" characters in the edit field. The user will type
"around" the literal characters as they fill in the "blanks" created by the placeholders.
Here are the special characters that you can use in an input mask:
(Note that some of them are special literal characters that adapt to the user's system
settings.)
. Decimal placeholder. (Special literal.) This will be replaced by the character specified as the
decimal placeholder in the user's international settings. To force a period on all systems,
use \. instead.

, Thousands separator. (Special literal.) This will be replaced by the character specified as the
thousands separator in the user's international settings. To force a comma on all systems,
use \, instead.

: Time separator. (Special literal.) This will be replaced by the character specified as the time
separator in the user's international settings. To force a colon on all systems, use \: instead.

/ Date separator. (Special literal.) This will be replaced by the character specified as the date
separator in the user's international settings. To force a slash on all systems, use \/ instead.

# Digit placeholder (0-9). For every # in the input mask, the user will only be able to enter a
digit between 0 and 9. To display a literal number sign (#), use \# instead.

A Alphanumeric character placeholder (0-9 and a-Z). For every A in the input mask, the user
will be able to enter any letter from a to z or any digit between 0 and 9. To display a literal
"A", use \A instead.

? Alphabetic placeholder (a-Z). For every ? in the input mask, the user will only be able to
enter a letter from a to z. To display a literal question mark, use \? instead.

> Alphabetic placeholder, but forces any letters typed to uppercase (A-Z). For every > in the
input mask, the user will only be able to enter a letter from a to z, and whatever letter they
type will be converted to uppercase. To display a literal greater-than sign, use \> instead.

< Alphabetic placeholder, but forces any letters typed to lowercase (a-z). For every < in the
input mask, the user will only be able to enter a letter from a to z, and whatever letter they
type will be converted to lowercase. To display a literal less-than sign, use \< instead.

& Character placeholder. Allows any ANSI character in the following ranges: 32-126 and 128-
255. To display a literal ampersand, use \& instead.

\ Literal escape. Use this to make a special character act as a literal in the input mask.

For example, you could create a mask for an IP address:

IP \Address\: ###\.###\.###\.###

...which would appear as:

IP Address:    .   .   .   

(Note that we needed to use the literal escape for the 'A' in Address, the colon, and all three
decimal points.)

You might also like