27.10.2015 Views

AJAX and PHP

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

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

Chapter 4<br />

Always validate user input on the server.<br />

The application you are about to build validates a registration form, as shown in Figure 4.2, using<br />

both <strong>AJAX</strong> validation (client side) <strong>and</strong> typical server-side validation:<br />

• <strong>AJAX</strong>-style—when each form field loses focus (onblur). The field's value is sent to<br />

the server, which validates the data <strong>and</strong> returns a result (0 for failure, 1 for success).<br />

If validation fails, an error message will unobtrusively show up <strong>and</strong> notify the user<br />

about the failed validation as shown in Figure 4.3.<br />

• <strong>PHP</strong>-style—when the entire form is submitted. This is the usual validation you<br />

would do on the server, by checking user input against certain rules. If no errors are<br />

found <strong>and</strong> the input data is valid, the browser is redirected to a success page as<br />

shown in Figure 4.4. If validation fails, however, the user is sent back to the form<br />

page with the invalid fields highlighted as shown in Figure 4.3.<br />

Both <strong>AJAX</strong> validation <strong>and</strong> <strong>PHP</strong> validation check the entered data against these rules:<br />

• Username must not already exist in the database<br />

• Name field cannot be empty<br />

• A gender must be selected<br />

• Month of Birth must be selected<br />

• Birthday must be a valid date (between 1-31)<br />

• Year of birth must be a valid year (between 1900-2000)<br />

• The date must exist taking into consideration the number of days for each month<br />

• Email address must be written in a valid email format, such as filip@yahoo.co.uk or<br />

cristian@subdomain.domain.com<br />

• Phone number must be written in st<strong>and</strong>ard US form: xxx-xxx-xxxx<br />

• "I've read the Terms of Use" must be checked<br />

Watch the application in action in the following screenshots:<br />

123<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!