Database Reference
In-Depth Information
The prevalence of these issues in data-transfer problems means that you'll probably end
up writing some of your own validators on occasion to handle very specific date formats.
Other sections of this chapter can provide additional assistance. For example,
Recipe 12.10 covers conversion of two-digit year values to four-digit form, and
Recipe 12.11 discusses how to perform validity checking on components of date or time
values.
You might be able to save yourself some work by using existing date-checking modules
for your API language. Some possibilities: the Perl Date module; the Ruby date module;
the Python datetime module; the PHP DateTime class; the Java GregorianCalendar
and SimpleDateTime classes.
12.7. Using Patterns to Match Email Addresses or URLs
Problem
You want to determine whether a value looks like an email address or a URL.
Solution
Use a pattern, tuned to the desired level of strictness.
Discussion
The immediately preceding sections use patterns to identify classes of values such as
numbers and dates, which are fairly typical applications for regular expressions. But
pattern matching has much more widespread applicability for data validation. To give
some idea of a few other types of values for which pattern matching can be used, this
section shows a few tests for email addresses and URLs.
To check values that are expected to be email addresses, the pattern should require at
least an @ character with nonempty strings on either side:
/.@./
That's a pretty minimal test. It's difficult to come up with a fully general pattern that
covers all the legal values and rejects all the illegal ones, but it's easy to write a pattern
that's at least a little more restrictive. For example, in addition to being nonempty, the
username and the domain name should consist entirely of characters other than @
characters or spaces:
/^[^@ ]+@[^@ ]+$/
You may also want to require that the domain name part contain at least two parts
separated by a dot:
/^[^@ ]+@[^@ .]+\.[^@ .]+/
Search WWH ::




Custom Search