Dynadot

Automatic Form Validation

Spaceship Spaceship
Watch
Impact
0
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
Code:
<!--//
/* This script is open source, free for use and modification.  
 * Please leave this notice in tact to credit the author.
 * Author: Steven Moseley
 * Homepage: [url]http://www.stevenmoseley.com[/url]
 */

// 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:
Code:
<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:
  1. 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.
  2. 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.
  3. 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).
  4. 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!

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!
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
Hey That looks nice! :D I'm sure I could put that to use. I think I'll have to give it a try some time.
 
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back