Loading
Hosting Unlimited Indonesia

Not-So-Simple Validation

Not-So-Simple Validation

Let's talk a bit about using regular expressions with the ereg() and eregi() functions. As I said earlier, these
can be either quite complex or very simple, depending on what you need.

Using regular expressions, you can examine a string and intelligently search for patterns and variations to
see whether they match the criteria you set. The most common of these involves checking whether an
email address is valid (although, of course, there's no fail-safe way of doing this).

Rather than delve into the mysteries of regular expressions, I'll provide some examples. You can use the
same form we created on the previous page - just paste in the lines below to see how they work.

First, let's make sure that text only has been entered into a form element. This regular expression tests
true if the user has entered one or more lowercase characters, from a to z. No numbers are allowed:

if (!ereg("[a-Z]", $first) || !ereg("[a-Z]", $last)) {
Now, let's extend this expression to check whether the string is four to six characters in length. Using
[[:alpha:]] is an easy way to check for valid alphabetic characters. The numbers in the braces check for
the number of occurrences. And note that the ^ and $ indicate the beginning and end of the string.

if (!ereg("^[[:alpha:]]{4,6}$", $first) || !ereg("^[[:alpha:]]{4,6}$", $last)) {
Finally, let's build a regular expression that will check an email address' validity. There's been plenty of
discussion about the effectiveness of checking for email addresses in this way. Nothing's completely
foolproof, but what I have below works pretty well.

I took this gem from the PHP mailing list. It's a great resource - use it. And yes, this is as scary as it looks.
f (!ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'.
'@'.
'[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
'[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $last)) {

Don't spend too much time looking at this. Just move on to the next page.

0 Comments:

Post a Comment

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Top WordPress Themes