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.
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;
}