Validation Rule
Validation Rule
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.
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.
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
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.
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 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.
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.
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?
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.
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.
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
-or-
You must enter a positive number.
BETWEEN 0 AND 1 Enter a value with a percent sign. (For use with a field that stores
number values as percentages).
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.
NOT Tests for converse values. Use before any comparison NOT > 10 (the same as <=10).
operator except IS NOT NULL.
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
= Equal to.
Validatin Rule
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?
CHARACTE EXPLANATION
R
# User can enter a digit, space, plus or minus sign. If skipped, Access enters a blank space.
.,:;-/ Decimal and thousands placeholders, date and time separators. The character you select depends on your
Microsoft Windows regional settings.
! Causes the input mask to fill from left to right instead of from right to left.
TOP OF PAGE
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.
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
5. Click the Build button to start the Input Mask Wizard, and then follow the instructions in the wizard.
Top of section
4. Click theBuild button to start the Input Mask Wizard, and then follow the instructions in the wizard.
Top of section
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.
(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.
>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.
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.
IP \Address\: ###\.###\.###\.###
(Note that we needed to use the literal escape for the 'A' in Address, the colon, and all three
decimal points.)