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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

324<br />

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

Matching one or more characters is good for verifying that at least one character was entered. For<br />

instance, if you want to verify that a user enters at least one character into a form input <strong>and</strong> that the<br />

character is a valid word character, you can use this pattern to validate the input: /\w+/.<br />

Finally, matching a specific range of characters is especially useful when matching numeric ranges.<br />

For instance, you can use this pattern to ensure a value is between 0 <strong>and</strong> 99: /\b\d{1,2}\b/.<br />

In your example file, you use this regex pattern to find any words consisting of exactly four letters:<br />

/(\b\w{4}\b)/ (see Figure 9-7).<br />

Figure 9-7. Matching only words that consist of exactly four letters<br />

Detecting the Beginning or End of a String<br />

Additionally, you can force the pattern to match from the beginning or end of the string (or both). If the<br />

pattern starts with a caret (^), the regex will only match if the pattern starts with a matching character. If<br />

it ends with a dollar sign ($), the regex will match only if the string ends with the preceding matching<br />

character.<br />

You can combine these different symbols to make sure an entire string matches a pattern. This is<br />

useful when validating input because you can verify that the user only submitted valid information. For<br />

instance, you can you can use this regex pattern to verify that a username contains only the letters A-Z,<br />

the numbers 0-9, <strong>and</strong> the underscore character: /^\w+$/.<br />

Using Alternation<br />

In some cases, it’s desirable to use either one pattern or another. This is called alternation, <strong>and</strong> it’s<br />

accomplished using a pipe character (|). This approach allows you to define two or more possibilities for<br />

a match. For instance, you can use this pattern to match either three-, six-, or seven-letter words in<br />

regex.php: /\b(\w{3}|\w{6,7})\b/ (see Figure 9-8).

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

Saved successfully!

Ooh no, something went wrong!