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.

C H A P T E R 9<br />

■ ■ ■<br />

Performing Form Validation<br />

with Regular Expressions<br />

It’s your responsibility as a developer to ensure that your users’ data is useful to your app, so you need to<br />

ensure that critical information is validated before storing it in your database.<br />

In the case of the calendar application, the date format is critical: if the format isn’t correct, the app<br />

will fail in several places. To verify that only valid dates are allowed into the database, you’ll use regular<br />

expressions (regexes), which are powerful pattern-matching tools that allow developers much more<br />

control over data than a strict string comparison search.<br />

Before you can get started with adding validation to your application, you need to get comfortable<br />

using regular expressions. In the first section of this chapter, you’ll learn how to use the basic syntax of<br />

regexes. Then you’ll put regexes to work doing server-side <strong>and</strong> client-side validation.<br />

Getting Comfortable with Regular Expressions<br />

Regular expressions are often perceived as intimidating, difficult tools. In fact, regexes have such a bad<br />

reputation among programmers that discussions about them are often peppered with this quote:<br />

Some people, when confronted with a problem, think, “I know, I’ll use regular<br />

expressions.” Now they have two problems.<br />

—Jamie Zawinski<br />

This sentiment is not entirely unfounded because regular expressions come with a complex syntax<br />

<strong>and</strong> little margin for error. However, after overcoming the initial learning curve, regexes are an<br />

incredibly powerful tool with myriad applications in day-to-day programming.<br />

Underst<strong>and</strong>ing Basic Regular Expression Syntax<br />

In this book, you’ll learn Perl-Compatible Regular Expression (PCRE) syntax. This syntax is compatible<br />

with <strong>PHP</strong> <strong>and</strong> JavaScript, as well as most other programming languages.<br />

311

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

Saved successfully!

Ooh no, something went wrong!