Skip to Main Content
Learning PHP, MySQL, and JavaScript
book

Learning PHP, MySQL, and JavaScript

by Robin Nixon
July 2009
Beginner content levelBeginner
526 pages
14h 24m
English
O'Reilly Media, Inc.
Content preview from Learning PHP, MySQL, and JavaScript

Validating User Input with JavaScript

JavaScript validation should be considered an assistance more to your users than to your websites because, as I have already stressed many times, you cannot trust any data submitted to your server, even if it has supposedly been validated with JavaScript. This is because hackers can quite easily simulate your web forms and submit any data of their choosing.

Another reason you cannot rely on JavaScript to perform all your input validation is that some users disable JavaScript, or use browsers that don’t support it.

So the best types of validation to do in JavaScript are checking that fields have content if they are not to be left empty, ensuring that email addresses conform to the proper format, and ensuring that values entered are within expected bounds.

The validate.html Document (Part One)

So let’s take a general sign-up form, common on most sites that offer memberships or registered users. The inputs being requested will be forename, surname, username, password, age, and email address. Example 17-1 provides a good template for such a form.

Example 17-1. A form with JavaScript validation (part one)
<html><head><title>An Example Form</title>
<style>.signup { border: 1px solid #999999;
    font: normal 14px helvetica; color:#444444; }</style>

<script>
function validate(form) {
    fail  = validateForename(form.forename.value)
    fail += validateSurname(form.surname.value)
    fail += validateUsername(form.username.value)
    fail += validatePassword(form.password.value) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Web Database Applications with PHP and MySQL, 2nd Edition

Web Database Applications with PHP and MySQL, 2nd Edition

Hugh E. Williams, David Lane
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 9780596803605Supplemental ContentErrata Page