Basics
Creating a Document
Head and Body Elements
Formatting Text
Creating Lists
Embedding Images
URLs Explained
Linking to Documents
Creating Tables
Forms Form Basics
Input and Textarea
Select Lists
Frames Framesets
The Frame Element
Nested Framesets
Targetting Frames
Inline Frames
Tips and Tricks Meta Tags
Transition Effects
HTML Generators Create a Document
Create a List
Create a Table
HTML
Basics
Implementing CSS
CSS Syntax
Pseudo Classes/Elements
CSS Classes
CSS Properties Font Properties
Color and Background
Text Properties
Border Properties
Margins and Padding
Size and Position
Tips and Tricks Menu Buttons
Special Effects
CSS
Basics
Running a Script
Variables
Expressions and Operators
Objects.Properties.Methods
The Date Object
Strings
Regular Expressions
Defining RegExp Patterns
Branches and Conditions
Loops
Arrays Array Basics
Array Methods
Sorting Arrays

User-Defined Functions
Cookies
Windows
Frames
Tips and Tricks Image Replacement
Using Includes
Form Validation
Debugging
JavaScript
Basics
Creating a Script
Running a Script
Variables
Expressions and Operators
Strings Strings Basics
Strings and Substrings
Replacing Substrings
Regular Expressions
Branches and Conditions
Loops
Arrays Array Basics
Array Functions
Sorting Arrays
User-Defined Functions
Include and Require
Uploading Files
File Functions
Session Variables
Tips and Tricks Page Templates
Form Reply Scripts
Form Validation
JavaScript to PHP
PHP
Basics
Create and Drop
Show and Describe
Insert, Update and Delete
Querying
Join Queries
Functions
Table Locking
PHP/MySQL Functions Accessing a Database
Querying with PHP
Create and Drop with PHP
Insert and Update with PHP
Frequently Used Functions MySQL
Basics
Layout and Navigation
Page Content Style
Web Page Copy
Graphics and Animation
HTML Forms
Accessibility
Legal Requirements
MySQL
JavaScriptBasicsRunning a ScriptVariablesExpressions and OperatorsObjects.Properties.MethodsThe Date ObjectStringsRegular ExpressionsDefining RegExp PatternsBranches and ConditionsLoopsArraysArray MethodsSorting ArraysUser-Defined FunctionsCookiesWindowsFrames

Home > JavaScript Tips and Tricks > Form Validationprinter version

JavaScript Form Validation

JavaScript can be usefully used to check if a user has correctly completed an HTML form prior to submission - and inform the user if they haven't.

The golden rule with forms is never trust user input and JavaScript validation shouldn't be considered as a substitute for server-side validation using PHP, which can filter out malicious input.

Using the Document Object Model

As covered in the tutorial on Objects, Properties and Methods, the DOM holds a map of all HTML objects in a page - including form objects.

Therefore if you give the form, and each field within it, unique names, these can be referred to from within a JavaScript function to read and validate the fields.

Creating the HTML Form

The example below is a simple form with two fields for first name and second name and the only validation will be to check if either of these fields has been left blank.

The form tag includes an onsubmit event that will call a function, called form_check, to validate the fields in the form.

A Basic Form Example using Input
<form action="myform.php" method="post" name="details" onsubmit="return form_check()">
    First Name:
    <input type="text" size="50" name="first_name">
    Second Name:
    <input type="text" size="50" name="second_name">
    <input type="submit" name="Send">
</form>


Creating the Event Handler

Now to create the function, called form_check(), to act as the event handler. This will check the fields within the form and return false if any of the fields don't validate.

The function will also include JavaScript alert boxes to inform the user which field has a problem and what the problem was.

When the form is submitted the onsubmit event calls the function, using return, and if false is returned then the form won't submit.

The Function form_check()
<script language="javascript" type="text/javascript">
    function form_check()
    {
        if(document.details.first_name.value=="")
        {
            alert("First Name required");
            return false;
        }

        if(document.details.second_name.value=="")
        {
            alert("Second Name required");
            return false;
        }
    }
</script>


The example uses only a simple check for blank fields but a more sophisticated check, for example validating an email address, could be implemented using Regular Expressions.

The Complete Script
<html>
<head>
<script language="javascript" type="text/javascript">
    function form_check()
    {
        if(document.details.first_name.value=="")
        {
            alert("First Name required");
            return false;
        }

        if(document.details.second_name.value=="")
        {
            alert("Second Name required");
            return false;
        }
    }
</script>
</head>
<body>
<form action="myform.php" method="post" name="details" onsubmit="return form_check()">
    First Name:
    <input type="text" size="50" name="first_name">
    Second Name:
    <input type="text" size="50" name="second_name">
    <input type="submit" name="Send">
</form>
</body>
</html>





Privacy | Terms | Contact | Links | Sitemap | RSS Feeds RSS and JavaScript Feeds
©2010 www.webdesignworkmate.co.uk all rights reserved 
Design and Production by smallbizonline website design © 2000-2010
Valid HTML 4.01! Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0Valid CSS!
Tips and TricksImage ReplacementUsing IncludesJavaScript form validationForm ValidationDebugging
Got any JavaScript Tips?
Send me your tip and if it's suitable I'll put it on the site, credit it to you and add a link back to your site.
Recommended Reading
Javascript the definitive guide

Javascript and DHTML cookbook

Pro javascript techniques

simply javascript