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.

338<br />

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

Figure 9-23. The error message displayed when invalid dates are supplied<br />

Adding Client-Side Date Validation<br />

For most users, JavaScript will be enabled. It’s far more convenient as a user to get instant feedback on<br />

the form, so you will add new <strong>jQuery</strong> functionality to validate date strings on the client side.<br />

Creating a New JavaScript File to Validate the Date String<br />

Because you’re going to continue to work with this script in the next chapter, you should put it in a<br />

separate file in the js folder called valid-date.js. This file will contain a function that is functionally<br />

equivalent to the _validDate() method in the Calendar class.<br />

It will accept a date to validate, check it against the date-matching regex pattern you wrote<br />

previously using match(), <strong>and</strong> then return true if a match is found or false if match() returns null.<br />

You build this function <strong>by</strong> inserting the following code into valid-date.js:<br />

// Checks for a valid date string (YYYY-MM-DD HH:MM:SS)<br />

function validDate(date)<br />

{<br />

// Define the regex pattern to validate the format<br />

var pattern = /^(\d{4}(-\d{2}){2} (\d{2})(:\d{2}){2})$/;<br />

}<br />

// Returns true if the date matches, false if it doesn't<br />

return date.match(pattern)!=null;<br />

■ Note The regex pattern is not enclosed in quotes. If you used quotes, the pattern would be stored as a string<br />

<strong>and</strong> interpreted accordingly—this would result in the script looking for an exact character match, rather than<br />

interpreting the regex pattern properly.

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

Saved successfully!

Ooh no, something went wrong!