Access 2007[c] The Missing Manual
4.3. Validation Rules
Input masks are a great tool, but they apply to only a few specific types of informationusually fixed-length text that has a single, unchanging pattern. To create a truly bulletproof table, you need to use more sophisticated restrictions, like making sure a number falls in a certain range, checking that a date hasn't yet occurred, or verifying that a text value starts with a certain letter. Validation rules can help you create all these restrictions by drawing on the full power of the SQL language. Note: You'll get a more thorough introduction to SQL starting in Chapter 6. Fortunately, you need only a dash of SQL to write a validation rule. The key ingredient's a validation expression , and you'll see several practical examples of expressions that you can drop straight into your tables. A validation rule's premise is simple. You set up a restriction that tells Access which values to allow in a field and which ones are no good. Whenever someone adds a new record or edits a record, Access makes sure the data lives up to your validation rules. If it doesn't, then Access presents an error message and forces you to edit the offending data and try again. 4.3.1. Applying a Field Validation Rule
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:
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 in Section 4.1.1.) To avoid these headaches , set up your validation rules before you start adding data. 4.3.2. Writing a Field Validation Rule
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 in Section 4.1.1. 4.3.2.1. 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-4. Expressions for Numbers
4.3.2.2. 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:
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, in Section 7.2.6. Table 4-4 has some examples. Table 4-5. Expressions for Dates
4.3.2.3. Validating text
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. in Section 7.2.5, you'll learn how to use functions that can snip out bits of text, test lengths, check capitalization, and more. 4.3.2.4. 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 than1000: >1000 Or <-1000
4.3.3. Creating a Table Validation Rule
Field validation rules always apply to a single field. However, database designers often need a way to compare the values in different fields. Suppose you have an Orders table that logs purchases from your monogrammed sock store. In your Orders table, you use two date fields: DateOrdered and DateShipped. To keep everything kosher, you need a validation rule that makes sure DateOrdered falls before DateShipped. After all, how can you ship a product out before someone orders it? Because this validation rule involves two fields, the only way to put it in place is to create a validation rule for the whole table. Table validation rules can use all the SQL tricks you've learned about so far, and they can pull the values out of any field in the current record. Here's how to create a table validation rule:
When you insert a new record, Access checks the field validation rules first. If your data passes the test (and has the right data types), then Access checks the table validation rule. Tip: Once you set the table validation rule, you might want to close the Property Sheet to get more room in your design window. To do so, choose Table Tools Design | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||