PDA

View Full Version : Automatic Form Validation


smoseley
July 28 '03, 11:41 AM
This is less of a tutorial than a freeware script and instructions on how to use it, but I didn't know where else to post it, so here ya go! This is a little system that I invented that uses Javascript / DOM with custom element properties to automatically validate a form when it is submitted.

To implement it, you will first need to create a Javascript file called "forms.js", with the following content:

forms.js

<!--//
/* This script is open source, free for use and modification.
* Please leave this notice in tact to credit the author.
* Author: Steven Moseley
* Homepage: http://www.stevenmoseley.com
*/

// Validates all fields in the specified form
function validate(form) {
var elements = form.getElementsByTagName('*');
var input = null;
var ok = true;
// Search for invalid inputs
for (var i = 0; i < elements.length; i++) {
input = elements[i];
minLength = (input.minlength) ? input.minlength : 0;
if (input.required == 'true') {
if (input.tagName.toLowerCase() == 'select') {
if (input.options.length == 0 ||
!input[input.selectedIndex].value) {
ok = false;
}
} else if (!input.value || input.value.length < minLength) {
ok = false;
}
if (!ok) {
window.alert('Please complete field "' + input.title + '"');
try {
input.focus();
} catch (e) {
}
return false;
}
}
if (input.confirm && input.confirm != '') {
if (input.value != document.getElementById(input.confirm).value) {
window.alert(document.getElementById(input.confirm).title
+ ' and ' + input.title + ' do not match.');
return false;
}
}
}
return true;
}

// Focuses on the first <input> or <select> field in the specified form
function focusForm(formId) {
var elements = (formId)
? document.getElementById(formId).getElementsByTagName('*')
: document.getElementsByTagName('*');
for (var i = 0; i < elements.length; i++) {
input = elements[i];
if (input.tagName.toLowerCase() == 'input' ||
input.tagName.toLowerCase() == 'select') {
input.focus();
break;
}
}
return true;
}

//-->


Now that you have the script in place, it's time to create your form:

<head>
<script language="javascript" type="text/javascript" src="forms.js">
</script>
</head>
<body onload="focusForm('registrationForm')">
<form id="registrationForm" method="post" action="process.jsp"
onsubmit="return validate(this)">
<p class="form">
*Username<br />
<input type="text"
id="txtLogin" name="login" maxlength="32"
title="Username" required="true" />
</p>
<p class="form">
*Password<br />
<input type="password"
id="pwdPassword" name="password"
title="Password" required="true"
minlength="8" maxlength="16" />
</p>
<p class="form">
*Confirm<br />
<input type="password"
id="pwdConfirm" name="confirm"
title="Confirm" required="true"
confirm="pwdPassword" />
</p>
<p class="form">
*First Name<br />
<input type="text"
id="txtFirstName" name="first_name" maxlength="255"
title="First Name" required="true" />
</p>
<p class="form">
*Last Name<br />
<input type="text"
id="txtLastName" name="last_name" maxlength="255"
title="Last Name" required="true" />
</p>
<p class="form">
*Email Address<br />
<input type="text"
id="txtEmail" name="email" maxlength="255"
title="Email Address" required="true" />
</p>
<p class="form">
*User Type<br />
<select
id="cboUserTypeId" name="user_type_id"
title="User Type" required="true">
<option></option>
<option value="1">Administrator</option>
<option value="2">Member</option>
</select>
</p>
<button type="submit">Save</button>
</form>
</body>

There are a few custom properties that are in use here:

required - This property can have a value of "true" or "false". If set to "true", the automatic validation script will detect it and check to see that a value has been entered / selected.
confirm - This property is used to confirm a field (such as a password). It contains a value equating to the id property of the field to be confirmed. When the form is submitted, the validation will check that the two fields match.
minlength - This property is used to add functionality to a field where you want a specified minimum number of characters (such as a password field).
title - This property is used to store the display name of the field for error messages.

When a field is incorrectly filled, an alert pops up telling the user to correctly fill the field.

Basically, what this system does is augment HTML forms to increase their functionality and usability. Form checking is usually a tedious process to implement, so people get lazy with it. This script allows you do put client-side form-checking into your web app simply and easily. Just include the script in the head of your document and you're good to go!

smoseley
July 28 '03, 11:55 AM
Also, I forgot to mention... the form will auto-focus on the first field if you include the "focusForm()" funciton in the body onload event (which I have done in this example).

Additionally, when an exception is encountered in one of the fields, it will focus on the problem field after the alert message is closed out by the user, increasing usability even more!

filburt1
July 28 '03, 12:36 PM
+20TD for you ;)

smoseley
July 28 '03, 01:07 PM
Thanks :)
Did you try the scriopt?

filburt1
July 28 '03, 03:33 PM
Too busy ATM with work.

GrandmasterB
July 28 '03, 07:53 PM
transio...that's excellent. I've been wanting to add more stringent validation to my forms and this is perfect.

BIG UPS TO TRANSIO.

Brak
July 28 '03, 09:01 PM
That's a great one.. I've got a custom script of my own that I use a lot... however a note to new users: Client side form checking is NOT a secure way to make sure your users aren't going to screw something up. Always double check on the server-side because people can disable javascript really easiely.

cinq
July 28 '03, 09:49 PM
This is a very cool script, I just made use of it for a feedback form. thanks for posting it transio :D

A point to note is that in the code for the form , where it says :


<form id="registrationForm" method="post" action="process.jsp"
onsubmit="return validate(this)">


The action would have to depend on what you are trying to do.

In my case, my feedback form would email the comments from user feedback to me.
Thus i set it up such that :


action="<?php echo "$PHP_SELF"?>"


and in the feedbackform.php, set up the mail function accordingly when the submit button is clicked.

May be obvious to some but just tot it may be of help to others trying to figure this script out .
HTH :)

Brak
July 28 '03, 10:00 PM
Qucick tip cinq: <?=$variable?> works the same as <?php echo $variable?>

smoseley
July 28 '03, 10:33 PM
yeah, you could get away with

action="<?=$PHP_SELF?>"

filburt1
July 28 '03, 10:37 PM
Technically you should always use:

action="<?php echo $_SERVER['PHP_SELF']; ?>"

because
1. <?= can be disabled
2. <? can be disabled (over <?php)
3. It has a semicolon at the end
4. It doesn't use the deprecated $PHP_SELF