02.06.2013 Views

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

328<br />

CHAPTER 9 ■ PERFORMING FORM VALIDATION WITH REGULAR EXPRESSIONS<br />

Figure 9-14. The completed regular expression<br />

■ Tip The examples in this chapter go over the most common features of regular expressions, but they don’t<br />

cover everything that regexes have to offer. Jan Goyvaerts has put together a fantastic resource for learning all of<br />

the ins-<strong>and</strong>-outs of regexes, as well as some tools for testing them, at<br />

http://www.regular-expressions.info/.<br />

Adding Server-Side Date Validation<br />

Now that you have a basic underst<strong>and</strong>ing of regexes, you’re ready to start validating user input. For this<br />

app, you need to ensure that the date format is correct, so that the app doesn’t crash <strong>by</strong> attempting to<br />

parse a date that it can’t underst<strong>and</strong>.<br />

You’ll begin <strong>by</strong> adding server-side validation. This is more of a fallback because later you’ll add<br />

validation with <strong>jQuery</strong>. However, you should never rely solely on JavaScript to validate user input<br />

because the user can easily turn off JavaScript support <strong>and</strong> therefore completely disable your JavaScript<br />

validation efforts.<br />

Defining the Regex Pattern to Validate Dates<br />

The first step toward implementing date validation is to define a regex pattern to match the desired<br />

format. The format the calendar app uses is YYYY-MM-DD HH:MM:SS.<br />

Setting up Test Data<br />

You need to modify regex.php with a valid date format <strong>and</strong> a few invalid formats, so you can test your<br />

pattern. Start <strong>by</strong> matching zero or more numeric characters with your regex pattern. Do this <strong>by</strong> making<br />

the following changes shown in bold:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!