HTML and CSS Reference
In-Depth Information
Because postal codes aren't case sensitive, the expression allows the first character to be
either uppercase or lowercase. The next character in the postal code must be a digit:
Because the postal code accepts all digits 0-9, \d is used to specify any digit. However,
[0-9] could have been used as well. And now the pattern continues, letter-number-letter
As was indicated earlier, the space in the middle of the postal code, while common
convention, is optional. This is where deciding how flexible the data validation should be is
required. The expression as it is won't allow for any space in the middle because the expres-
sion is set to match on consecutive alternating letter-number-letter. Perhaps, for formatting
purposes, a space should be required. In this case, \s would require that a space is included:
Now, users would be required to enter the postal code with a space in the middle of the
two sets of three characters. But maybe the website doesn't care about the space in the
middle, because it doesn't really affect anything. In this case, the \s can be denoted with the *:
Now, the expression allows for alternating letter-number-letter and one or more spaces
can occur in the middle. The space is now optional, but a problem has been introduced. The
user can now enter any number of spaces and still pass the validation, such as:
A1A 1A1
That would pass the validation because one or more spaces is required by the \s*. The
desired outcome here is to allow only one space or no spaces. For this, a new element is
added to limit the number of occurrences to just one. This is accomplished by specifying the
maximum length allowed for the character set being matched:
The {1} says to match the previous character only the specified number of times—in this
case, one time. Now the expression is back to functionality that's no different than just speci-
fying the \s. What is needed next is something to make the single space optional, as denoted
with the ?. To achieve this effect, the space segment is wrapped in square brackets to make it
a set and followed by the ? to make it optional:
Now you have a regular expression that requires the correct alphanumeric pattern for a
Canadian postal code with an optional space in the middle.
This simple example demonstrates the key elements to a regular expression. Although this
regular expression can be placed into the pattern attribute of the <input> element, this next
Search WWH ::

Custom Search