Wednesday, May 02, 2007

looking into forms

The first screen you'll need to build for a login application will be a simple form that asks for a user name and password.

To save the server unneccessary work, and your web visitor unneccessary delays while they wait for an answer, it would be good to have some way of preventing the form from being submitted until the visitor has entered both a name and a password.

We do this by writing some client side script which checks the form before it gets sent to the server. If it finds that either the name and/or the password fields are blank it should alert the user and let them remedy the situation before sending the form off.

Here's a blow-by-blow analysis...

Calling a script when the submit button is pressed

First we need a function to call. In the head section of your login form page, add the following script:

function validateForm(){
alert('we're now validating the form');


And in the form tag of your page add an ONSUBMIT attribute that calls the function:

<FORM ONSUBMIT="return validateForm();">

Onsubmit is an 'event' that gets called when someone clicks on the submit button for a form. Try this out in your form and you should see an alert box when you click on the submit button.

Preventing the form from being submitted

If you had sharp eyes you might have noticed that the value for the onsubmit attribute said: "return validateForm();" - it returned a value picked up from the validateForm function to the browser.

If that value is 'false' then the browser will not process the form any further.

Don't just take my word for this, try it out by adding the following line to your validateForm function:

function validateForm(){
alert('we're now validating the form');
return false;

Now try submitting your form with some values in it and you should see that they stay there when you try to submit the form. It won't get submitted because you're passing the 'false' value that validateForm sends back through to the browser.

Checking for a form value

All well and good so far, but we still haven't got anything that checks the value our user's typed into the form.

To do this we need to add a little more code.

Firstly, we'll need to be able to identify our form elements. We do this by adding id attributes to the input tags, something like:

<input type="text" id="name" />

We can see the value in this field now by calling a JavaScript function: getElementById.

Try it by replacing your validateForm function with the following code:

function validateForm(){
alert('hello '+document.getElementById('name').value);
return false;

Type something in the name field of the form and submit it and you should see the name pop up in an alert box.

Go ahead now and add an ID and some JavaScript code to show the password in the same way.

Checking for empty fields

From here it's a simple task to check for an empty field and optionally show an error message.

Try this code in your validateForm function...

function validateForm(){
if (document.getElementById('name').value == '') {
alert('you must enter a user name');
return false;

Test it with and without anything in the user name field, then add some code that checks for a password in the same way.

Reducing user frustration

If you've gotten this far you probably have a script that brings up two alert messages if the user submits with both fields empty.

It would be better to just show one message with all the errors listed together. It would also be good if the form submitted properly when they've entered the required information.

We can kill these two birds by building an error message string during the testing phase of our script, and then either displaying the error message if there is one, or returning 'true' and allowing the form to be submitted if there is no error message to show.

It should look something like this:

function validateForm(){
var errormessage = '';
if (document.getElementById('name').value == '') {
errormessage = 'you must enter a user name';
if (document.getElementById('password').value == '') {
errormessage += 'you must enter a password';
if (errormessage == '') {
retrun true;
} else {
return false;


Let's look at what's going on here.

We start out by creating a variable called errormessage and assigning it an empty string (the two single quote marks side by side)

Then we look to see if there's any user name entered. If there isn't, we set the error message to prompt the user for one.

Next we check for a value in the password field. This time, if we find nothing, we add a message to whatever is already in the errormessage variable. By using the += we're telling the program to add a string to anything that's already in the variable.

Finally, we check to see if there's anything in our errormessage variable. If there isn't we return true, which will tell the browser to go ahead and submit the form.

If there is a message, we display it and return 'false', preventing the form from being submitted.

Try it out. Add the code and test it with the 4 scenarios (nothing etnered; name or password only entered; and both name and password entered)


Just one little bit of tidying up to do.

Right now the error message for the 'nothing entered' case looks a bit ugly. To get the error messages appearing on seperate lines we need to add the newline character to our first error string:

errormessage = 'you must enter a user name\n';

There, now it's perfect :-)

Further reading

If you've still got some JavaScript curiosity left, I've put some pages up for you to read through. Try the first three JavaScript primers then take a well earned break.

Original image: 'The thief eats a seed'
by: Bob Travis

No comments: