About this Resource
[Skip navigation][Access key info]SEARCH | SITE MAP
SELF-STUDY INDEX
Exploring online research methods - Incorporating TRI-ORM

Form validation

[Skip instructions]

[i] Click on the headings to open them. They will open on this page. Open the following link for further information about these headings if required.

Your browser does not support these headings. To ensure that the contents remain accessible, they have been automatically opened so that all the information on the page is displayed.

However, to take advantage of the headings and to ensure that the layout and design of this site are displayed correctly, you are recommended to upgrade to a current version of one of the following standards compliant browsers:

Glossary links are included within this page. If a word appears as a link, clicking on this link will show the definition of the word in a 'pop-up window'. Select the following link for information about these glossary links if required.

  1. Select the links see the definitions in a pop-up window.
  2. NB. If you use pop-up window blocking software, you will need to deactivate it for pop-ups on this site to use the glossary links. Alternatively, all glossary definitions can be seen on the 'Glossary' page in the 'Resources' section.
  3. Use of the glossary links is JavaScript dependent. If JavaScript is disabled, it will be necessary to open the 'Glossary' page to view the definitions. Opening this page in a new window may allow you to refer more easily to the definitions while you navigate the site.

Open/close headingIntroduction

Using JavaScript, it is possible to check that data is in a suitable format, that any required questions have been answered, and that no questions or selections have been accidentally missed prior to submission. This page will provide an overview of the procedure for adding validation to check the data from common form elements. It is recommended that you review the 'Introduction to JavaScript' page and the section on 'simple validation' in particular before working through this page.

When deciding whether or not to add validation to a questionnaire, it is important to consider the effects it may have. Care must be taken when requiring answers to questions that participants may not wish to answer, as this is likely to lead to drop out. Requiring answers should generally only be considered where it is essential to the success of the questionnaire.

Rather than preventing submission of a questionnaire with incomplete answers, it may be appropriate to prompt the participant to check unanswered fields, giving the option of proceeding with the submission or going back to check. This may increase responses and is certainly more likely to deal with accidental omissions without leading to problems of requiring responses.

Client-side scripting via JavaScript has a great advantages over server-side processing when performing validation as it allows an instant response to any problems with the form submission. It is not necessary for the form information to be submitted to the server and then sent back; the processes happen on the user's computer.

However, It is also important to bear in mind that JavaScript may reduce the accessibility of the questionnaire. Users of text-only or screen-reading browsers are likely to be unable to access any functionality provided by JavaScript, and it is also possible that it may not be fully supported in the user's browser or that he or she may have chosen to deactivate it. For this reason, it is important to ensure that the use of the questionnaire does not depend on JavaScript, and to 'back up' any validation via JavaScript with server-side validation once the form is submitted. This is likely to enhance the security as well as the accessibility of the questionnaire. For more information, see the 'accessibility' and 'server-side validation' sections below.

 

Close heading CLOSE

Open/close headingExample of 'once-only' text box validation

The following is an example of a web form with simple validation applied to a text box. It prevents submission of the form unless 'M,' 'm,' 'F' or 'f' is entered for the question.

It is designed to allow submission the second time the submit button is pressed regardless of whether or not the question has been answered appropriately.

[?] Submit the form leaving some answers out or answering them inappropriately to check how it functions.

What is your gender (M or F)?

The HTML and JavaScript behind the form is as follows:

Open/close headingThe body

 

[?] The body of the HTML document is shown below. Check your understanding of how the HTML creates and names the form and form elements, and provides them with attributes and values where required. Review the 'Web forms' section if necessary.

 

<body>

<form name="genderCheck" action="" method="post" onSubmit="return checkForm(this);">

<p>What is your gender (M or F)?</p>
<p><input type="text" name="genderbox" size="1" maxlength="1" /></p>

<p><input type="submit" name="Submit" value="Submit" /></p>

</form>

</body>

Open/close headingLearning activity: Triggering validation

[?] Check your understanding of how the form triggers and responds to the validation routines by answering the following questions and selecting 'check answers' to view suggested answers in a new window.

Review 'simple validation' in the 'Introduction to JavaScript' section if necessary.

1. When is the validation triggered?

2. What is the name of the function that performs the validation?

3. Two valid values can be returned to the form tag following validation routines. What are these values and what effect do they have?

Check Answers

 

Close heading CLOSE

 

Close heading CLOSE

Open/close headingThe validation script

The script makes use of a variable (initially set to 'false') which is used to check whether or not the user has attempted to submit the form previously (it is changed to 'true' on the first submission).

If this is the case (or if the form has been completed correctly the first time the submission is attempted) the submission is allowed to proceed ('true' is returned to the form).

Otherwise, the submission is blocked ('false' is returned to the form) and the variable is changed to 'true' to allow it to proceed next time.

The script is shown below with comments explaining each section of code.

It is common to add these comments to JavaScript code to provide an explanation of how it works. They are ignored by the browser, but can be viewed in the source code of the HTML document or the JavaScript file. Comments in JavaScript should be prefixed by two forward-slashes (//) to ensure that the browser ignores them.

[?] Check your understanding of the code by reading the comments. Review the 'Introduction to JavaScript' section if necessary.

 

<script language="javascript" type="text/javascript">

// Set variable for whether submit has been pressed (Placed outside the function so that its value will not be set to false every time the function is called, but will be 'remembered'

var submitPressed = false;

// start function and tell it to expect the name and reference to the form to be passed into it (to replace the word 'form') when the function is called

function checkForm(form) {

// Check the submission - If the question has been answered correctly (the box contains 'm', 'M', 'f', or 'F') or if the user has already tried to submit once before (genderSubmitPressed is 'true'), provide the user with a thank-you alert and return 'true' to the form to allow submission to proceed.

if (submitPressed == true || form.genderbox.value =="m" || form.genderbox.value =="M" || form.genderbox.value =="f" || form.genderbox.value =="F") {
alert("Thank you for completing the form.");
return true;
}

// In any other situation, deliver an alert box message to the user reminding them to answer the question. Change the submitPressed variable to 'true' to allow submission to proceed next time and return 'false' to the form to prevent submission this time.

else {
alert("Please insert your gender which is needed for analysis purposes and which will not compromise the anonymity of your data. If you would rather not provide this information, press the submit button again to proceed.");
submitPressed = true;
return false;
}

// end function

}
</script>

In a situation where the researcher wishes to require an answer to the question and not allow submission at the second attempt, this could easily be done by removing the three references to the 'submitPressed' variable in the code (var submitPressed = false;, submitPressed == true ||, and submitPressed = true;).

 

Close heading CLOSE

 

Close heading CLOSE

Open/close headingRadio buttons

It is also possible to check that one of a group of radio buttons has been checked as follows:

How often do you use the internet?

everyday
2-3 days per week
4-5 days per week
6-7 days per week
less than once a week

This is made possible by the fact that all of the radio buttons have the same name and are thus automatically included in an array. This means that each of the buttons is given a number starting with zero. These numbers can be used to refer to each Check box using the following syntax:

form.often[x]

where x is the number of the button and where form is replaced by the name and reference to the form (e.g. window.document.formname) which is passed into the function when it is called.

The HTML for the radio buttons is as follows:

<input type="radio" name="often" value="everyday" />
everyday<br />
<input type="radio" name="often" value="2-3 days per week" />
2-3 days per week<br />
<input type="radio" name="often" value="4-5 days per week" />
4-5 days per week<br />
<input type="radio" name="often" value="6-7 days per week" />
6-7 days per week<br />
<input type="radio" name="often" value="less than once a week" />
less than once a week </p>

The reference to the first button is:

form.often[0]

while the reference to the last (the fifth) is:

form.often[4]

Each radio button has a property checked which has a value true or false. This can be used to ascertain whether it has been selected (checked is true) or has not been selected (checked is false).

The section of the validation script that checks whether one of the buttons has been selected is as follows:

if (form.often[0].checked == true || form.often[1].checked == true || form.often[2].checked == true || form.often[3].checked == true || form.often[4].checked == true){

alert("Thank you for completing the form.");
return true;

}

This displays the thank-you message and returns true to the form to allow submission to proceed in the following circumstances:

circumstances code
button 1 has been selected: form.often[0].checked == true
or: ||
button 2 has been selected: form.often[1].checked == true
or: ||
button 3 has been selected: form.often[2].checked == true
or: ||
button 4 has been selected: form.often[3].checked == true
or: ||
button 5 has been selected: form.often[4].checked == true

This can be simplified by looping through each of the boxes to check whether or not they have been selected, as follows:

for (var i = 0; i < form.often.length; i++){

if (form.often[i].checked == true){
questionAnswered = true;
}

}

if (questionAnswered == true){

alert("Thank you for completing the form.");
return true;

}

This begins a loop which feeds the value of i into the conditional (if (form.often[i].checked == true))

The initial value of i is set to 0 (var i = 0;) and it is set to increase by one at the end of each loop (i++) until i is no longer less than the length of the array of Check boxes called often (i<form.often.length;) which in this case is five (there are five boxes).

This means that the conditional (if (form.often[i].checked == true)) is carried out five times with i replaced with 0, 1, 2, 3, and 4.

In each case, if the button has been selected, a variable questionAnswered is set to true.

This is followed by another conditional which displays the thank-you message and returns true to the form if questionAnswered is true.

The complete code is as follows:

<script language="javascript" type="text/javascript">

// Set variable for whether submit has been pressed

var submitPressed = false;

// start function

function checkForm(form) {

// Set variable for whether question has been answered

var questionAnswered = false;

// Check the submission - If any of the buttons have been selected, change 'questionAnswered' variable to 'true'.

for (var i = 0; i<form.often.length; i++){

if (form.often[i].checked == true){
questionAnswered = true;
}

}

// If 'submitPressed' is 'true' (the submit button has already been pressed) or 'questionAnswered' is 'true' (an option has been selected), provide the user with a thank-you alert and return 'true' to the form to allow submission to proceed.

if (submitPressed == true || questionAnswered == true){

alert("Thank you for completing the form.");
return true;

}

// In any other situation, deliver an alert box message to the user reminding them to answer the question. Change the submitPressed variable to 'true' to allow submission to proceed next time and return 'false' to the form to prevent submission this time.

else {

alert("Please select an answer. If you would rather not provide this information, press the submit button again to proceed.");
submitPressed = true;
return false;

}

// end function

}
</script>

 

Close heading CLOSE

Open/close headingCheck boxes

Like radio buttons, a group of check boxes can be given the same name. In this case, they can be validated in the same way as radio buttons using the array which automatically numbers the boxes.

Which of the following do you regularly use the internet for?

E mail
Finding information about things to buy
Making purchases
Entertainment
Finding general information
Educational courses
Downloading music
Discussion boards
Real-time chat

The HTML for the Check boxes is as follows:

<p>Which of the following do you regularly use the internet for?</p>
<p>
<input type="Check box" name="uses" value="email" />
E mail<br />
<input type="Check box" name="uses" value="finding information about things to buy" />
Finding information about things to buy<br />
<input type="Check box" name="uses" value="making purchases" />
Making purchases<br />
<input type="Check box" name="uses" value="entertainment" />
Entertainment<br />
<input type="Check box" name="uses" value="finding general information" />
Finding general information<br />
<input type="Check box" name="uses" value="educational courses" />
Educational courses<br />
<input type="Check box" name="uses" value="downloading music" />
Downloading music<br />
<input type="Check box" name="uses" value="discussion boards" />
Discussion boards<br />
<input type="Check box" name="uses" value="real-time chat" />
Real-time chat</p>
<p>

The Check boxes are given the same name (uses), but different values. When the form is submitted, the value of any checked box can be added to a variable. Each of the different values is added separated by a comma. Thus, for example, if the first three Check boxes are selected, the variable will be :

"email, finding information about things to buy, making purchases"

The code for checking that an option has been selected is exactly the same as that for the radio buttons, except that the name given to the Check boxes is added to the loop and conditionals, as follows:

for (var i = 0; i<form.uses.length; i++){

if (form.uses[i].checked == true){
questionAnswered = true;
}

}

This is a key advantage of using the loop to check each of the radio buttons or check boxes rather than including a conditional for every button or box. The same piece of code can be used for each group regardless of the number of boxes, with the only necessary modification being the name.

 

Close heading CLOSE

Open/close headingSelect boxes

Select boxes can be validated in a similar way to radio buttons and Check boxes, as the options in a box are also counted in an array.

How would you rate your skill as an internet user?

The HTML for the select box is as follows:

<p>How would you rate your skill as an internet user?</p>
<p>
<select name="skill">
<option value="not answered">Select an option</option>
<option value="not answered">-------------------</option>
<option value="very advanced">Very advanced</option>
<option value="advanced">Advanced</option>
<option value="average">Average</option>
<option value="basic">Basic</option>
<option value="very basic">Very basic</option>
</select>
</p>
<p>

It is given the name skill and each option is given an appropriate value. The options are counted in an array as follows:

form.skill.options[x]

where x is the number of the option (starting from 0) and where form is replaced by the name and reference to the form (e.g. window.document.formname) which is passed into the function when it is called.

Thus, the reference to the first option (labeled 'Select an option' and given the value 'not answered') is:

form.skill.options[0]

while the reference to the last (the seventh, labeled 'Very basic' and given the value 'very basic') is:

form.skill.options[6]

The first option provides the instruction to the user (Select an option), and the second acts as a divider between this and the options proper(-------------------). Thus, it can be assumed that if either of these options is selected, the question has not been answered.

It is therefore possible to check that a valid option has been selected through the following code:

// Check the submission - If both the first and second options have not been selected, provide the user with a thank-you alert and return 'true' to the form to allow submission to proceed.

if (form.skill.options[0].selected != true && form.skill.options[1].selected != true) {

alert("Thank you for completing the form.");
return true;

}

 

Close heading CLOSE

Open/close headingValidating multiple form elements

As with the previous examples, the following questionnaire prevents the first submission of the form unless all the questions have been answered and allows submission the second time the submit button is pressed regardless of whether or not all the questions have been answered appropriately.

In this case, however, there is more than one form element, so it is helpful to inform the user of which question(s) need attention. This is done through delivery of an alert-box message when a problem is found.

[?] Complete the web form leaving some answers out or answering them inappropriately (they will be dealt with client side and will not be sent away from your computer).

1. What is your name?

2. How often do you use the internet?

everyday
2-3 days per week
4-5 days per week
6-7 days per week
less than once a week

This is done through the use of extra variables which are set to record which questions have not been answered and to add the question numbers to the alert box message.

The code for this is shown in the following learning activity.

Open/close headingLearning activity: Validating multiple elements

[?] This activity will allow you to check your understanding of how the code works, by matching the comments to the sections of code that they describe. It will also act as a review of once-only validation of textboxes and radio buttons. There is a text-only alternative to this activity below if required.

Open/close headingText-only alternative

[?]This activity will allow you to check your understanding of how the code works, by matching the comments to the sections of code that they describe. It will also act as a review of once-only validation of textboxes and radio buttons.

Match the pieces of code (A-H) to the comments theat describe them (1-8).

Code

<script language="javascript" type="text/javascript">

A
var submitPressed = false;
var q1Answered = false;
var q2Answered = false;
var alertMessage = "";

// start function

function checkForm(form) {

B
else{

q1Answered = true;

}

C
for (var i = 0; i<form.often.length; i++){

if (form.often[i].checked == true){
q2Answered = true;
}

}

D
if (q2Answered == false){

alertMessage = alertMessage + "2 ";

}

E
if (submitPressed == true || (q1Answered == true && q2Answered == true)){

alert("Thank you for completing the form.");
return true;

}

F
else {

alert("Please check your answers to the following question(s):\n\r" + alertMessage + "\n\rIf you are happy with them, press the submit button again to proceed with the submission.");

}

G
submitPressed = true;
return false;
}

// end function

}
</script>

Comments

  1. // Check question 1 - If the box is empty, the question has not been answered. In this case, add the question number to the message that will be delivered to the user to indicate that there are problems with certain questions.
  2. // If both questions have been answered (q1Answered and q2Answered are both true) or if the user has already tried to submit once before (submitPressed is true), provide the user with a thank-you alert and return 'true' to the form to allow submission to proceed.
  3. // If either or both of the questions has not been answered, deliver an alert box message to the user and include the variable 'alertMessage' which was used to collect the numbers of the unanswered questions.
  4. // Change the submitPressed variable to true to allow submission to proceed next time and return 'false' to the form to prevent submission this time.
  5. // If 'q2Answered' is still false, the question has not been answered, so add the question number to the message.
  6. // If the box is not empty, the question has been answered, so the 'q1Answered' variable is changed to 'true'.
  7. // Check question 2 - If any of the buttons have been selected, change 'q2Answered' variable to 'true'.
  8. // Set variables
    // Variable for whether submit has been pressed
    // Variable for whether each question has been answered
    // Variable for the final alert box message.

 

Open/close headingAnswers

A=8
B=1
C=6
D=7
E=5
F=2
G=3
H=4

Complete code:

<script language="javascript" type="text/javascript">

// Set variables
// Variable for whether submit has been pressed
// Variable for whether each question has been answered
// Variable for the final alert box message.

var submitPressed = false;
var q1Answered = false;
var q2Answered = false;
var alertMessage = "";

// start function

function checkForm(form) {

// Check question 1 - If the box is empty, the question has not been answered. In this case, add the question number to the message that will be delivered to the user to indicate that there are problems with certain questions.

if (form.namebox.value ==""){

alertMessage = "1 ";

}

// If the box is not empty, the question has been answered, so the 'q1Answered' variable is changed to 'true'.

else{

q1Answered = true;

}

// Check question 2 - If any of the buttons have been selected, change 'q2Answered' variable to 'true'.

for (var i = 0; i<form.often.length; i++){

if (form.often[i].checked == true){
q2Answered = true;
}

}

// If 'q2Answered' is still false, the question has not been answered, so add the question number to the message.

if (q2Answered == false){

alertMessage = alertMessage + "2 ";

}

// If both questions have been answered (q1Answered and q2Answered are both true) or if the user has already tried to submit once before (submitPressed is true), provide the user with a thank-you alert and return 'true' to the form to allow submission to proceed.

if (submitPressed == true || (q1Answered == true && q2Answered == true)){

alert("Thank you for completing the form.");
return true;

}

// If either or both of the questions has not been answered, deliver an alert box message to the user and include the variable 'alertMessage' which was used to collect the numbers of the unanswered questions.

else {

alert("Please check your answers to the following question(s):\n\r" + alertMessage + "\n\rIf you are happy with them, press the submit button again to proceed with the submission.");

}

// Change the submitPressed variable to true to allow submission to proceed next time and return 'false' to the form to prevent submission this time.

submitPressed = true;
return false;
}

// end function

}
</script>

 

Close heading CLOSE

 

Close heading CLOSE

 

Close heading CLOSE

A summary of the working of the code is as follows:

The text box and radio button validation routines shown in the sections above are carried out, but where a question has been answered a variable for that question is set to true rather than the submission occurring immediately. Where a question has not been answered, the submission is not immediately blocked, but the number of that question is added to a variable which is then incorporated into an alert-box message.

Finally, both the question variables are checked and where they are found to be true (i.e. they have been answered) or where the form has been submitted once before (the form submission variable is found to be true) a thank-you message is delivered. If any question variable is false, the alert-box message is delivered and the form submission variable is changed to true.

The complete code is as follows:

<script language="javascript" type="text/javascript">

// Set variables
// Variable for whether submit has been pressed
// Variable for whether each question has been answered
// Variable for the final alert box message.

var submitPressed = false;
var q1Answered = false;
var q2Answered = false;
var alertMessage = "";

// start function

function checkForm(form) {

// Check question 1 - If the box is empty, the question has not been answered. In this case, add the question number to the message that will be delivered to the user to indicate that there are problems with certain questions.

if (form.namebox.value ==""){

alertMessage = "1 ";

}

// If the box is not empty, the question has been answered, so the 'q1Answered' variable is changed to 'true'.

else{

q1Answered = true;

}

// Check question 2 - If any of the buttons have been selected, change 'q2Answered' variable to 'true'.

for (var i = 0; i<form.often.length; i++){

if (form.often[i].checked == true){
q2Answered = true;
}

}

// If 'q2Answered' is still false, the question has not been answered, so add the question number to the message.

if (q2Answered == false){

alertMessage = alertMessage + "2 ";

}

// If both questions have been answered (q1Answered and q2Answered are both true) or if the user has already tried to submit once before (submitPressed is true), provide the user with a thank-you alert and return 'true' to the form to allow submission to proceed.

if (submitPressed == true || (q1Answered == true && q2Answered == true)){

alert("Thank you for completing the form.");
return true;

}

// If either or both of the questions has not been answered, deliver an alert box message to the user and include the variable 'alertMessage' which was used to collect the numbers of the unanswered questions.

else {

alert("Please check your answers to the following question(s):\n\r" + alertMessage + "\n\rIf you are happy with them, press the submit button again to proceed with the submission.");

}

// Change the submitPressed variable to true to allow submission to proceed next time and return 'false' to the form to prevent submission this time.

submitPressed = true;
return false;
}

// end function

}
</script>

You can select the following link to view the HTML page and code in a new window. You can then select VIEW -> SOURCE if you wish to see or copy the complete HTML file.

 

Close heading CLOSE

Open/close headingPutting it all together

[i] This section contains examples of validation of a questionnaire with multiple questions and question types. The complete code for each method shown can be viewed in the 'Adapting the code' section below.

The following questionnaire about internet use incorporates all of the different validation elements outlined above.

[?] Complete the web form leaving some answers out and consider any possible problems with the way the validation works (they will be dealt with client side and will not be sent away from your computer).

1. What is your name?

2. How old are you?

years

3. What is your gender (M or F)?

4. How often do you use the internet?

everyday
2-3 days per week
4-5 days per week
6-7 days per week
less than once a week

5. Which of the following do you regularly use the internet for?
(You can select as many options as you like. If you would like to remove a selection you have made, select it again to deselect it).

E mail
Finding information about things to buy
Making purchases
Entertainment
Finding general information
Educational courses
Downloading music
Discussion boards
Real-time chat

6. How would you rate your skill as an internet user?

7. What, in your opinion, are the three main advantages of the internet?

A potential problem with the way the questionnaire is validated is that a single message is delivered to the user which includes all the questions requiring attention. This is not ideal as the user is unlikely to be able to remember which questions need to be checked in cases where there is more than one or two. Two more complex possible alternatives are shown below.

Open/close headingAlternative 1: One-by-one validation

In this case, each question is checked individually. If a question has not been answered or previously submitted, an alert message is displayed to the participant, and false is returned to the form to prevent submission. A variable for that question is also set to true so that submission will not be blocked if the participant resubmits without answering the question for a second time.

If the first question has been answered or has been submitted before, the second is checked. If this has been answered or previously submitted, the third is checked. This continues until all have been checked and a thank-you message is then delivered.

[?] Complete the web form leaving some answers out (they will be dealt with client side and will not be sent away from your computer).

1. What is your name?

2. How old are you?

years

3. What is your gender (M or F)?

4. How often do you use the internet?

everyday
2-3 days per week
4-5 days per week
6-7 days per week
less than once a week

5. Which of the following do you regularly use the internet for?
(You can select as many options as you like. If you would like to remove a selection you have made, select it again to deselect it).

E mail
Finding information about things to buy
Making purchases
Entertainment
Finding general information
Educational courses
Downloading music
Discussion boards
Real-time chat

6. How would you rate your skill as an internet user?

7. What, in your opinion, are the three main advantages of the internet?

A potential problem with the way this questionnaire is validated is that it tends to overuse alert messages. Where a number of questions have not been answered, the participant may become frustrated by this, which could lead to increased drop-out rates. However, it is no more difficult to implement and adapt for different questionnaires than the first example.

 

Close heading CLOSE

Open/close headingAlternative 2: Displaying messages within the questionnaire

This alternative is similar to the first example in that all the questions are checked together. The questionnaire prevents the first submission of the form unless all the questions have been answered and allows submission the second time the submit button is pressed regardless of which questions may not have been answered appropriately.

Rather than delivering an alert-box message with the numbers of the questions that have not been answered correctly, however, a message is revealed next to the questions on the questionnaire itself.

[?] Complete the web form leaving some answers out (they will be dealt with client side and will not be sent away from your computer).

1. What is your name?

2. How old are you?

years

3. What is your gender (M or F)?

4. How often do you use the internet?

everyday


6-7 days per week
less than once a week

5. Which of the following do you regularly use the internet for?
(You can select as many options as you like. If you would like to remove a selection you have made, select it again to deselect it).

E mail
Finding information about things to buy
Making purchases
Entertainment
Finding general information
Educational courses
Downloading music
Discussion boards
Real-time chat

6. How would you rate your skill as an internet user?

7. What, in your opinion, are the three main advantages of the internet?

This probably provides the most effective validation in terms of usability, but there may be problems for participants using older browsers (with version numbers lower than Netscape Navigator 5 or Internet Explorer 4) who may not be able to access the messages.

For this reason, an alert box message is included indicating that there is a problem with the answers. For users with a browser capable of displaying them, this is backed up with the messages indicating where the problems are. However, those who cannot access these messages are still informed of the reason for the failed submission, prompted to check their answers, and given the message that pressing the submit button a second time will allow it to proceed.

Thus, while the use of the messages adds to the functionality of the questionnaire, it does not prevent it from being usable for those who are unable to access it (see 'accessibility' section).

The messages are revealed using <div> and <span> tags in the HTML code with CSS and JavaScript. Implementing and adapting this method of presenting the results of validation is slightly more involved that the previous examples, but the validation routines are very similar to those of the first example.

 

Close heading CLOSE

Open/close headingAdapting the code

The complete HTML and JavaScript for each of the three questionnaires shown in this section can be seen by selecting the links at the end of this section. The code can then be saved, or copied and pasted into your text editor for adaption and use in questionnaires with different types and numbers of questions. There are explanatory comments in the code and some general notes on adaptation are as follows:

  1. When removing questions, make sure that associated code and variables are also removed.
  2. When adding validation to new questions, be sure to copy in full the associated code and variables from a question of the same type.
  3. When adding form elements for new questions, give them a unique name and make sure that this is added correctly into the code copied from similar questions.
  4. Similarly, make sure that new variable names are unique and added correctly into all relevant parts of the code.
  5. Ensure that you have included the required punctuation, or the code may not run correctly. For example, make sure that functions are contained within curly brackets ({}), and that conditionals are within brackets, with actions resulting from conditionals in curly brackets. See the 'Introduction to JavaScript' section of this guide for further information if required.

 

[i] Select the following links to view the HTML pages in a new window. You can then select VIEW -> SOURCE if you wish to see or copy the complete HTML/JavaScript file.

Questionnaire 1: Alert-box message

Questionnaire 2: One-by-one validation

Questionnaire 3: Validation via messages within the questionnaire

 

Close heading CLOSE

 

Close heading CLOSE

Open/close headingValidating before submission

The following form applies validation routines before the submit button is pressed. For both questions, participants are prevented from selecting more than three options, and for question 2, they are also limited to entering '1', '2', or '3' in the text boxes.

[?] Complete the web form to check how the validation works. Consider how this could be achieved using some of the validation techniques above.

1. Choose THREE adjectives that you think best describe successful websites?
If you would like to change a selection you have made, select it again to deselect it.

Easy to use
Attractive
Functional
Fast
Well-known
Colourful
Dynamic
Interactive
Simple
Varied
Up-to-date

2. From the following list of potential disadvantages of the internet, choose the THREE which you consider to be the most serious.
Then rank them by writing the numbers 1, 2 and 3 in the boxes. 1 = Most serious, 3 = least serious.

It is expensive
It is too slow
It provides information that is mainly of poor quality
It offers too much information
It wastes too much time
It can expose the user's computer to virus attacks or hacking
There are too many adverts and/or to much junk email
There are often problems with broken links

Three different validation routines are carried out.

The first two routines are carried out independently of the submit button when participants are completing the questions. The first occurs as the result of an onclick event handler, when participants select a Check box. The second occurs as a result of an onblur event handler when participants click away from a text box. (see the information about event handlers in the 'Introduction to JavaScript' for more information if necessary).

This type of validation ensures that problems are dealt with before participants attempt to submit and also serves to provide on-going instructions to participants attempting to complete the questions.

Finally, there is a function called by pressing the submit button. This checks that three options have been selected for the questions and delivers an alert message if this is not the case.

Each of the routines is explained in the following sections:

Open/close heading'onclick' validation

The validation routine for question 1 consists of a function which is called by the onclick event handler when participants select the Check boxes.

Each of the eleven Check boxes is given the same name (adjectives) which means that they are automatically added to an array from zero to ten. They are also given appropriate values so that when the form is submitted the value of checked boxes can be added to the adjectives variable. The onclick event handler is added to each which calls a function called count() and returns the result of this function to the Check box. If true is returned, the Check box is selected, and if false is returned, it is deselected. (This works in a similar way to returning true or false to a form when it is submitted). Thus, the HTML for the first and second Check boxes is:

<input type="Check box" name="adjectives" value="easy" onclick="return count(this.form)" />
Easy to use<br />
<input type="Check box" name="adjectives" value="attractive" onclick="return count(this.form)" />
Attractive<br />

When participants select a box, the function counts the number of checked boxes, returning false (deselecting the box) if three boxes have already been selected, and returning true allowing the box to remain selected) if fewer than three have been selected. The commented code is as follows:

// start function and tell it to expect the name and reference to the form to be passed into it (to replace the word 'form') when the function is called.

function count(form) {

// Set variable called 'number' used to count the number of Check boxes selected. This is contained within the function, so it is 'local' to the function. Thus, it is 'reset' to 0 each time the function is called and does not 'remember' between function calls. A variable with the same name can be included in a different function without interfering with this one.

var number = 0;

// Start a loop to check each of the boxes. For each box, check if it is selected, and if so, add 1 to the 'number' variable.

for (i = 0; i < form.adjectives.length; i++) {

if (form.adjectives[i].checked == true){
number = number+1;

}

}

// Check the 'number' variable. If it is less than 4, return 'true' so that it stays checked.

if (number < 4) {

return true;
}

// If it equals 4 (the Check box clicked would be the fourth to be selected), return 'false' so that it is deselected.

else if (number ==4) {

return false;
}

}

 

Close heading CLOSE

Open/close heading'onblur' validation

The routine for question 2 consists of a function called check2() which is called by the onblur event handler when participants click away from a text box. The counting of the text boxes that have been filled in occurs in a similar way to the routine in question 1.

However, the text boxes cannot be given the same name, as it would not be possible to distinguish which ones have been chosen. Thus they cannot be counted in an array. Instead of this, it is possible to use the form.elements array to count the boxes. This is an array of all the form elements in a form. The first to appear is given the number zero (form.elements[0]) and the second is given the number one (form.elements[1]). This continues for all the elements in the form.

By counting how many elements come before the first text box in question 2, and counting how many text boxes there are, we can find the number of the boxes in this form.elements array and use this information in the validation routine. There are 11 Check boxes in question 1 (form.elements[0]) to (form.elements[10]) and there are 8 textboxes in question 2. Thus the first textbox in question 2 is the 12th in the form.elements array (form.elements[11]) and the last is the 20th (form.elements[19]).

This means that the routine needs to check the 12th to the 20th elements and count the ones that have been filled, preventing more than three from being filled. This is similar to the code in the routine for question 1. However, the number of the box in the element.array must be fed into the function as an argument so that the box that called the function can be identified.

Thus, there are two arguments in the function (the form reference and the number of the box in the array), and the HTML for the first two boxes is as follows:

<p> It is expensive
<input type="text" maxlength="1" size="1" name="expensive" onblur="count2(this.form, 11)" /><br />
It is too slow
<input onblur="count2(this.form, 12)" type="text" maxlength="1" size="1" name="slow" />

and the function is begun and ended as follows:

function count2(form, box) {

}

The section of the function that counts the boxes is as follows:

// Set variable called 'number' used to count the number of textboxes filled.

var number = 0;

// Start a loop to check each of the boxes. For each box, check if it is filled (its value is not an empty string(""), and if so, add 1 to the 'number' variable.

for (i = 11; i < 19; i++) {

if (form.elements[i].value !=""){
number = number+1;

// Check the 'number' variable. If it is has reached 4 (this is the fourth box to be filled), delete the contents of the last box to be filled in (by changing the value of the box which called the function to "") and provide an alert message.

if (number == 4){

form.elements[box].value ="";
alert("Please select three options only. Delete one of your selections if you would like to change it.");
}

}

}

// NB. It is important to check that all curly brackets that have been opened are closed correctly, or the script will not run correctly.

This provides the facility of limiting the number of responses to three, but it does not limit what the contents of the boxes can be.

To do this, it is necessary to check that only the numbers 1, 2 and 3 have been entered in the boxes, and to ensure that these numbers have been entered only once.

Three variables are set to count the number of times that 1, 2 and 3 have been entered and if a box that calls the function is found to contain a number for the second time, the contents are deleted and a message delivered to the participant. This also occurs if any other content is inserted into the box.

The commented code for this section of the function is as follows:

// Set variables called 'onePicked', 'onePicked', and 'onePicked' used to count the number of occurrences of 1, 2 and 3.

var onePicked = 0;
var twoPicked = 0;
var threePicked = 0;

// Start a loop to check each of the boxes.

for (j = 11; j < 19; j++) {

// For each box, check if the value is "1", and if so, add 1 to the 'onePicked' variable. If it has reached 2 ('onePicked is greater than 1), delete the contents of the last box to be filled in (by changing the value of the box which called the function to "") and provide an alert message.

if (form.elements[j].value =="1") {

onePicked = onePicked +1;
if (onePicked >1){
form.elements[box].value ="";
alert("Please select rank 1 for one option only");
}

}

// Do the same for value "2".

else if (form.elements[j].value =="2") {

twoPicked = twoPicked +1;
if (twoPicked >1){
form.elements[box].value ="";
alert("Please select rank 2 for one option only");
}

}

// And for value "3".

else if (form.elements[j].value =="3") {

threePicked = threePicked +1;
if (threePicked >1){
form.elements[box].value ="";
alert("Please select rank 3 for one option only");
}

}

// Finally check that no other value has been added to the boxes, by checking for boxes that are not empty (and do not contain "1", "2" or "3". If any other value is found, delete the contents of the box, and give focus to it (place the cursor in the box) ready for the participant to add a different value.

else if (form.elements[j].value !=""){

alert("Please enter a number from 1-3");
form.elements[box].value ="";
form.elements[box].focus();
}

}

 

Close heading CLOSE

Open/close heading'onSubmit' validation

This is the most straightforward of the functions, because the more involved validation activities have been carried out beforehand. All that has to be done is to check that three options have been chosen for each question. If this is the case, it can be assumed that the validation from the other functions has already ensured the correct number and format of responses has been provided.

The commented code is as follows:

function checkForm(form) {

// Set variable used to count the number of Check boxes selected for question 1.

var number = 0;

// Start a loop to check each of the boxes in question 1. For each box, check if it is checked, and if so, add 1 to the variable.

for (i = 0; i < form.adjectives.length; i++) {

if (form.adjectives[i].checked == true){
number = number+1;

}

}

// At the end of the loop, check how many boxes have been selected. If it is not three, deliver an alert message and return 'false' to the form to prevent submission.

if (number != 3) {

alert("Please select three options for question 1.");
return false;

}

// Set variable used to count the number of text boxes filled in for question 2.

var number2 = 0;

// Start a loop to check each of the boxes in question 2. For each box, check if it is filled (it's value is not an empty string ""), and if so, add 1 to the variable.

for (j = 11; j < 19; j++) {

if (form.elements[j].value !="") {
number2 = number2+1;

}

}

// At the end of the loop, check how many boxes have been filled. If it is not three, deliver an alert message and return 'false' to the form to prevent submission.

if (number2 != 3) {

alert("Please select your three options for question 2.");
return false;

}

// If the code makes it to this stage without returning 'false' to the form, the correct number of responses have been made. Deliver a thank-you alert message and return 'true' to the form to allow submission to proceed.

alert("Thank you for completing the form.");
return true;

}

You can select the following link to view the HTML page and code in a new window. You can then select VIEW -> SOURCE if you wish to see or copy the complete HTML file.

 

Close heading CLOSE

 

Close heading CLOSE

Open/close headingAccessibility

Providing that submission of a questionnaire is not prevented in browsers without JavaScript, validation routines will not prevent a questionnaire from being accessible as they will simply not work. Though this may have an impact on the quality of the data received from a non-JavaScript browser (e.g. if participants using these browsers accidentally miss questions or answer them in an inappropriate format), it will not prevent the questionnaire from being fully usable by these participants.

However, it may be beneficial to perform server-side validation as a 'back up' to the client-side JavaScript validation. Because server-side processing occurs before the HTML page is delivered to the browser, it is not dependent on the technology available on the client computer. Although this is a slower method of checking the information, it is likely to be necessary only where JavaScript is not available and thus where any problems with the data have not been dealt with before the form is sent. This kind of 'back-up' validation also has security benefits where users may have deactivated JavaScript in the browser to avoid validation.

 

Close heading CLOSE

Open/close headingServer-side validation

Methods of validating in any of the main server-side languages are basically similar to those using JavaScript, involving conditionals to check the contents or selection of form elements and carrying out different actions accordingly (e.g. processing results by emailing them or by adding them to a database, or preventing processing and returning a message to the participant prompting them to check and resubmit).

An overview of server-side technologies and their use in gathering data via questionnaires can be found in the 'Server-side processing' section of this guide.

Depending on the technology used, the following links may provide a useful source of information, tutorials and examples on how to add server-side validation.

Open/close headingPHP/MySQL 

A PHP tutorial which covers a range of different validation activities, leading to an example of a complete form validated via PHP.
[External Link - opens in a new window] http://www.codewalkers.com/c/a/Miscellaneous/Form-and-Spelling-Validation/

Sklar, D. (2004) Learning PHP. Sebastapol, CA. O'Reilly.
Chapter 6: Making web forms.
[External Link - opens in a new window] http://www.oreilly.com/ catalog/learnphp5/

Sklar, D. and Trachtenberg, A. (2003) PHP Cookbook. Sebastapol, CA. O'Reilly.
Chapter 9: Forms.
[External Link - opens in a new window] http://www.oreilly.com/ catalog/phpckbk/

Coggeshall, J. (2005) PHP Unleashed. Indianapolis. SAMS.
Chapter 4: Working with Forms in PHP.
Chapter 5: Advanced Form Techniques.
[External Link - opens in a new window] http://www.samspublishing.com/ title/067232511X

Zandstra , M. (2005) Teach Yourself PHP in 24 Hours, 2nd Edition. Indianapolis. SAMS.
Chapter 9: Working with Forms (available as a sample chapter)
[External Link - opens in a new window] http://www.samspublishing.com/ title/0672323117

 

Close heading CLOSE

Open/close headingASP.NET

Microsoft's ASP.NET framework offers a number of ready-made web controls designed to carry out server-side and, where available, client-side validation of web forms. These include controls that check required fields have been completed, that check that data in particular ranges or patterns has been entered (e.g. in the format of a telephone or credit-card number), and that compare data from one form element for consistency with that from another.

A useful tutorial on how these controls work with code examples is available from the ASP.NET Quickstart tutorials
[External Link - opens in a new window] http://www.asp.net/ QuickStart/aspnet/ doc/validation/default.aspx

A step-by-step guide is also available from the 4guysfromrolla.com site:
[External Link - opens in a new window] http://www.4guysfromrolla.com/ webtech/090200-1.shtml

Mitchell, S. (2003) Teach yourself ASP.NET. Indianapolis. SAMS.
Chapter 12. Validating User Input with Validation Controls.
[External Link - opens in a new window] http://www.samspublishing.com/ title/0672325438#

Walther, S. (2003) ASP.NET. Unleashed. Indianapolis. SAMS.
Chapter 2: Building Forms with Web Server Controls.
Chapter 3: Performing Form Validation with Validation Controls.
[External Link - opens in a new window] http://www.samspublishing.com/ title/0672325438#

 

Close heading CLOSE

Open/close headingPERL/CGI 

An introductory tutorial for adding validation using PERL.
[External Link - opens in a new window] http://www.elated.com/ tutorials/ programming/ perl_cgi/ form_validation/

Colburn, R. (2003) Teach yourself CGI. Indianapolis. SAMS.
Chapter 7: Validating user input.
[External Link - opens in a new window] http://www.samspublishing.com/ title/0672324040

Guelich, S., Gundavaram, S. and Birznieks, G. (2000) CGI Programming with Perl. Sebastapol, CA. O'Reilly.
Chapter 4: Forms and CGI;
Chapter 8: Security (available as a sample chapter).
[External Link - opens in a new window] http://www.oreilly.com/ catalog/ cgi2/ toc.html

 

Close heading CLOSE

 

Close heading CLOSE

  © 2004-2010  All rights reserved    |    Maintained by ReStore    |    About this website    |    Disclaimer    |    Copyright    |    Citation policy    |    Contact us