List Info

Thread: Re: code desing - logic issue?




Re: code desing - logic issue?
country flaguser name
United States
2007-06-01 18:33:44

hello everyone:

I tried to use a counter to count how many elements on the form
passed validation test. (if all the elements passed validation test,
then submit the form. Otherwise don't submit the form)

But counter will not increment correctly. I think the cause is due to
the value of boolean variable validatedOK didn't get updated correctly!

In my switch statement: cases for "undergrad_account" and
"grad_account " didn't return boolean variable back to switch
statement, the associated validation function are called by using
onclick event handler. After the break statement, boolean variable
validatedOK remains 'true', the counter keeps increasing regardless if
checkboxes for graduate students' account being checked or not.

If you have time, please run my code and give me some suggestions
a)how to make it work properly.

b) Is there an alternative approach to validate elements on the form?
I used onSubmit event handler becuase it provides an opportunity to
check most elements on the form and return 'false' so the form won't
submit.

I appreciate your help!

HTML code:

<body onload=&quot;document.account_form.fname.focus()&quot;>
&lt;form name=";account_form" id="account_form" action=&quot;" method ="post"
onSubmit=&quot;return form_validation()&quot;>
First Name: &nbsp;&nbsp;<input type=";text" name=";fname"; id="fname"
value=&quot;" maxlength="20&quot;><;br /><br />
Last Name:&nbsp;&nbsp;&nbsp;&nbsp;<input type=";text" name=";lname";
id=&quot;lname&quot; value=&quot;" maxlength="20&quot;><;br /><br />

age: &nbsp;&nbsp;<input type=";text" name=";age" id="age" value=&quot;"
maxlength="3&quot;>&lt;br /><br />

<input type=";radio"; name=";gender&quot; id="maleR" value=&quot;male"; />Male <br
/><br />

<input type=";radio"; name=";gender&quot; id="femaleR"; value=&quot;female&quot; />Female
<br /><br />

<!-- selection list ----------------------->
<select name=";departments" id="departments&quot;>
<option value=&quot;none";>select your department</option>
&lt;option value=&quot;art">Arts&lt;/option&gt;
<option value=&quot;bio">Biology</option>
<option value=&quot;cs"&gt;Computer Science<;/option>;
<option value=&quot;eng">English</option>
<option value=&quot;math";>Mathematics</option>
<option value=&quot;geology&quot;>Geology</option>
<option value=&quot;history&quot;>History</option>
<option value=&quot;physics&quot;>Physics</option>
</select><br /><br />

Email&nbsp;&nbsp;<input type=";text" name=";email"; id="email" size=";30"
maxlength="30&quot; /><br /><br />
Phone Number&;nbsp;&;nbsp;<input type=";text" name=";phone_num"
id="phone_num" size=";14" maxlength="14&quot; />
(enter a phone number like 4084445566)<br /><br />

<!--
account selection - undergraduate or graduate students
enable/disable graduate account(checkboxes) - base on radio button
selection
-->

<!-- onclick=&quot;return checkAccountStatus(this.form)&quot; -->
&lt;input type=";radio"; name=";class_standing" id="under_graduate"
value=";under_graduate" onclick=&quot;checkAccountStatus()" />Undergraduate
student&;nbsp;&;nbsp;&nbsp;

<input type=";radio"; name=";class_standing" id="graduate&quot;
value="graduate" onclick=&quot;checkAccountStatus()" />Graduate student<;br
/><br />

<p>Accounts for All Student<;/p>
&lt;input type=";checkbox&quot; name=";undergrad_account&quot;
id=&quot;undergrad_account1&quot; value=&quot;dial_up&quot; />Dial Up<br />
&lt;input type=";checkbox&quot; name=";undergrad_account&quot;
id=&quot;undergrad_account2&quot; value=&quot;pc_lab&quot; />Computer Lab<br />
&lt;input type=";checkbox&quot; name=";undergrad_account&quot;
id=&quot;undergrad_account3&quot; value=&quot;music_movie" />Music/Movie Download&lt;br
/>;<br />

<p>Accounts for Graduate Student Only</p>

&lt;input type=";checkbox&quot; name=";grad_account" id="grad_account1"
value="dsl_account" onclick=&quot;checkGraduateAccount(this.form)" />DSL
Account<;br />
&lt;input type=";checkbox&quot; name=";grad_account" id="grad_account2"
value="unix_account" onclick=&quot;checkGraduateAccount(this.form)" />Unix
Account&lt;br />
&lt;input type=";checkbox&quot; name=";grad_account" id="grad_account3"
value="web_host&quot; onclick=&quot;checkGraduateAccount(this.form)" />Web
Hosting<;br />
&lt;input type=";checkbox&quot; name=";grad_account" id="grad_account4"
value="list_server" onclick=&quot;checkGraduateAccount(this.form)" />List
Server<;br /><br />

<P>comments on student account services&lt;/p>
<textarea name=";comments&quot; id="comments&quot; rows=";5" cols=";40"
wrap=";virtual&quot;><;/textarea&gt;

&lt;p>
&lt;input type=";submit&quot; name=";submit&quot; value=&quot;Submit&quot; />
&lt;input type=";reset"; name=";reset"; value=&quot;Reset&quot; />
&lt;/p>
</form&gt;
</body>

-------------JavaScript handle the form validation ------------------
var checked_counter = 0;

function form_validation()
{
var validatedOK="&quot;; //boolean variable used for return to calling
html file

with(document.account_form)
{

//note first_name_field is a reference to first name field
var first_name_field = document.getElementById("fname");

//alert(first_name_field.value);

var last_name_field = document.getElementById("lname");
var age_field = document.getElementById("age");

var male_field = (document.getElementById("maleR"));
var female_field = (document.getElementById("femaleR&quot;));

var phone_field = (document.getElementById("phone_num&quot;));

//for loop iteration based on how many elements on the form
// elements.length - 2 you don't want to check last 2
//elements on the form - submit and reset button

for(var i = 0; i<(elements.length - 2); i++)
{

switch(elements[i].name)
{
case "fname":
validatedOK= checkFirstName(first_name_field); //pass a
reference to first name field to function
break;

case "lname":
validatedOK= checkLastName(last_name_field);
break;

case "age&quot;:
validatedOK= checkAge(age_field);
break;

case "gender":
validatedOK= checkGender();
break;

case "departments&quot;:
validatedOK= checkDept();
break;

case "email":
validatedOK= checkEmail();
break;

case "phone_num":
validatedOK= checkPhone(phone_field);
break;

case "class_standing&quot;: //case statement for radio buttons
validatedOK= checkAccountStatus();
break;


case "undergrad_account": //case statement for undergrad
checkboxes
break;

case "grad_account&quot;: //case statement for graduate student
checkboxes
//skip checkbox verification for enable/disable checkbox purpose
break;

case "comments":
validatedOK= checkComments();
break;

default:
alert(&quot;no such element exist on the form");
break;
}

//after the switch statement if return value for
//validatedOk is false call a function to return false to html file
//so form won't get submitted
if (!validatedOK)
{
return false;
}

//increment the counter, when all the elements on the form
//has passed validation test, call same function
//return 'true' to html file, so form can be submitted
else
{
checked_counter++; //when checked_counter equals to
elements.length - 2
//this means every field has passed
validation test

alert(&quot;value of checked_acounter is: " + checked_counter);

if (checked_counter == elements.length - 2)
{
var status = true;
return status;
}
}

}//end of for loop


}//end of with statement

}//end of form_validation function

function checkFirstName(elementReference)
{
if(elementReference.value == "&quot;)
{
alert(&quot;First Name field is blank";);
return false;
}
else if(elementReference.value.length < 2 ||
elementReference.value.length > 15)
{
alert(&quot;First Name field should between 2 to 15 characters");
return false;
}
else
return true;
}

function checkLastName(elementReference)
{
if(elementReference.value == "&quot;)
{
alert(&quot;Last Name field is blank";);
return false;
}
else if(elementReference.value.length < 2 ||
elementReference.value.length > 15)
{
alert(&quot;Last Name field should between 2 to 15 characters");
return false;
}
else
return true;
}

/* ------ Function checkAge ------------------- */
function checkAge(elementReference)
{
var ageStr = elementReference.value;

var temp;
var age="";
var number_count = 0;
var strAge=&quot;";

//use for loop to go through the string get from name text field
for(var i = 0; i < ageStr.length; i++)
{
temp = ageStr.charAt(i);
if(!isNaN(temp)) //filter out character data in string keep the digits
{
age +=temp;
number_count++;
}
else
{
strAge += temp; //concatenate all characters in the string to strAge
}

}

//parse string into integer use Number function;
var intAge = Number(age);


//test to see if age field left blank
if(ageStr == "&quot;)
{
alert(&quot;age field is blank, please fill out the age field";);
return false;
}

//cases to handle user's entry is characters only
else if(number_count == 0 && ageStr.length == 1)
{
alert( strAge + " is an invalid entry. Please enter a number&quot;);
return false;
}

else if(number_count == 0 && ageStr.length == 2)
{
alert( strAge + " is an invalid entry. Please enter a number&quot;);
return false;
}

else if(number_count == 0 && ageStr.length == 3)
{
alert( strAge + " is an invalid entry. Please enter a number&quot;);
return false;
}

//test number entered by user is between 10 and 99
//when age field is left blank intAge became 0,
else if(intAge < 10 || intAge > 99)
{
alert ("please enter an age between 10 and 99");
return false;
}
else
return true;

}//end of function checkAge()

/* ------ Function checkGender ------------------- */
function checkGender()
{
var genderCtr = -1;

with(document.account_form)
{

var maleRadioButton = (document.getElementById("maleR"));
var femaleRadioButton = (document.getElementById("femaleR&quot;));

for(var i = 0; i < gender.length; i++)
{
if(gender[i].checked)
{
genderCtr = i;

}

}

if(genderCtr == -1)
{
alert(&quot;you must select either male or female&quot;);
return false;
}

else
return true;

}//end of with statement
}

/* ------ Function checkDept ------------------- */
function checkDept()
{
with(document.account_form)
{
var choice ="&quot;
var choiceCtr = -1;

for(var i = 0; i < departments.options.length; i++)
{
choice = departments.options[i];

//skip default selected item in option list
if(i == 0 && choice.selected)
continue;
else if(choice.selected)
choiceCtr = i;
}

if(choiceCtr == -1)
{
alert(&quot;you must select one department from the drop down menu.";);
return false;
}
else
return true;
}//end of with statement
}

/* function checkEmail */
function checkEmail()
{

with(document.account_form)
{
var at = "";
var dot =".&quot;;
var lat = email.value.indexOf(at);

var lstr = email.value.length;
var ldot = email.value.indexOf(dot);

var suffix = email.value.substring(email.value.lastIndexOf(dot)+1);

if(!email.value)
{
alert(&quot;You left email address field blank. Please fill in your
email address.&quot;);
return false;
}

//test three cases:
//a) eamil address doesn't contain '' sign
//b)email address contain only ''
//c) '' sign is at the end of the string
else if(lat == -1 || lat == 0 || lat == (lstr - 1) )
{

alert(&quot;Email address is incomplete or invalid? corret email
address format-- name%40domain.com">namedomain.com.");
return false;
}

/*test three cases:
* a) email address string doesn't contain dot sign
* b) email address string contain dot sign at the very begining of
the string
* c) email address string contain dot sign at the very end
*
*/

else if(ldot == -1 || ldot == 0 || ldot == (lstr - 1) )
{
alert(&quot;Email address is incomplete or invalid? corret email
address format-- name%40domain.com">namedomain.com.");
return false;
}

/* test to ensure there should be only one '' in the email string */
else if( email.value.indexOf(at, lat + 1) != -1 )
{
alert(&quot;There should be only one '' sign in your email address&quot;);
return false;
}

/* test if dot sign apper in right position in email address
substring(lat-1,lat) --> detect if dot appears right before sign

// ?? str.substring(lat3;1,lat+;2) -- detect if dot appears right
after sign
not quite sure how str.substring(lat3;1,lat+;2)
*/
else if (email.value.substring(lat-1,lat)== dot ||
email.value.substring(lat+1,lat&#43;2)== dot)
{
alert(&quot;the dot sign appeared in wrong position in eamil address&quot;);
return false;
}

/*
search two character position after sign, if not dot sign found
return false
//??not sure how this one works
*/
else if (email.value.indexOf(dot,(lat&#43;2))== -1)
{
alert(&quot;dot sign didn't show after two character position after
sign&quot;);
return false;
}

//detect white space in it
else if (email.value.indexOf(" ")!= -1)
{
alert(&quot;email address can not contain white space in it");
return false;
}

//check for valid suffix for domain name
else if(suffix.length != 2 && suffix != 'com' && suffix != 'net' &&
suffix != 'org'
&& suffix != 'edu' && suffix != 'int' && suffix != 'mil' && suffix
!= 'gov' && suffix != 'arpa'
&& suffix != 'biz' && suffix != 'aero' && suffix != 'name' &&
suffix != 'coop' && suffix != 'info'
&& suffix != 'pro' && suffix != 'museum')
{
alert(&quot;invalid primary domain in email address&quot;);
return false;
}
else
return true;
}//end of with statement

}

/*
function checkPhone
*/
function checkPhone(elementReference)
{

with(document.account_form)
{
var phone_num = elementReference.value
var numPattern = /^ddd$/;
var mathedOK = phone_num.value.match(numPattern);

if(!phone_num)
{
alert(&quot;you left phone field blank. please enter a valid phone
number like 4085556677");
return false;
}


else if(!mathedOK)
{
alert(&quot;you entered invalid phone number. please enter a valid
phone number like 4085556677");
return false;
}

return true;

}//end of with statement

}

/*
function disableGraduateAccount()

*/
function disableGraduateAccount(frm)
{
for(var k = 0; k < frm.grad_account.length; k++)
{
frm.grad_account[k].disabled = true;
}
}

function enableGraduateAccount(frm)
{
for(var j = 0; j < frm.grad_account.length; j++)
{

frm.grad_account[j].disabled = false;
}

}

/*
checkAccountStatus
enable/disable graduate account(checkboxes) - base on radio button
selection
parameter: frm represent form object that contains the
under_graduate radio button
*/
function checkAccountStatus(frm)
{
with(document.account_form)
{
var classCtr = -1;

for(var i = 0; i < class_standing.length; i++)
{
if(class_standing[i].checked && class_standing[i].value ==
'under_graduate')
{
classCtr = i;
disableGraduateAccount(class_standing[i].form)
}

else if(class_standing[i].checked && class_standing[i].value ==
'graduate')
{
classCtr = i;
enableGraduateAccount(class_standing[i].form);
}
}

if(classCtr == -1)
{
alert(&quot;you must select either Undergraduate or Graduate radio
button.");
return false;
}

else
return true;

}//end of with statement

}

/*
function checkGraduateAccount
*/
function checkGraduateAccount(frm)
{
var gradAccountCtr = 0;
for(var i = 0; i < frm.grad_account.length; i++)
{

if(frm.grad_account[i].checked)
{

gradAccountCtr++;
}

}

if(gradAccountCtr > 2)
alert(&quot;only two accounts available for graduate student.&quot;);

else if(gradAccountCtr == 0)
alert(&quot;You didn't choose any account. Please select two accounts
if you are a graduate student.&quot;);

}

/*
Function checkComments - verify that textarea is not left blank
*/
function checkComments()
{
with(document.account_form)
{
if(!comments.value)
{
alert(&quot;You left comments field blank. Please provide some
comments.";);
return false;
}

else
{
return true;

}
}

}

Jeff
6-1-07

--- In JavaScript_Official%40yahoogroups.com">JavaScript_Officialyahoogroups.com, "David Smart";
<smartware.consulting...> wrote:
&gt;
> No - we've deleted it. Ask your question again.
&gt;
> Regards, Dave S
>

__._,_.___
.

__,_._,___
Re: code desing - logic issue?
country flaguser name
United States
2007-06-02 15:09:42

There is a logical error here:

if (!validatedOK)
{
return false;
}

//increment the counter, when all the elements on the form
//has passed validation test, call same function
//return 'true' to html file, so form can be submitted

else
{
checked_counter&#43;+;
//when checked_counter equals to elements.length - 2
//this means every field has passed validation test

alert(&quot;value of checked_acounter is: " + checked_counter);

if (checked_counter == elements.length - 2)
{
var status = true;
return status;
}
} // end else

The problem is that "checked_counter" is declared outside of the
functions. So imagine what happens when someone fills out the first
input field of your form correctly and then fills out the second one
incorrectly. The form won't submit (I think, I haven't gone through
the rest of the code) but "checked_counter" gets incremented every
time with one correct input field. If this happens enough times, that
is the user keeps entering one correct value and other values are
incorrect, the variable "checked_counter" will accumulate to the
point where it reaches "elements.length - 2".

The solution, if you have to do maintain a counter, is to put the
counter variable into the function so that it gets reset every time
the function is called.

Paul

__._,_.___
.

__,_._,___
Re: code desing - logic issue?
country flaguser name
United States
2007-06-02 15:14:12

Hi,

You really don't need all that looping and counting...
You could dispense with a lot of keyboard strokes and just do it this
way:

function form_validation()
{

// variables to hold form field references
var first_name_field = document.getElementById("fname");
var last_name_field = document.getElementById("lname");
var age_field = document.getElementById("age");
var male_field = document.getElementById("maleR");
var female_field = document.getElementById("femaleR";);
var phone_field = document.getElementById("phone_num&quot;);

if (!checkFirstName(first_name_field)){ return false }
if (!checkLastName(last_name_field)){ return false }
if (!checkAge(age_field)){ return false }
if (!checkGender()){ return false }
if (!checkDept()){ return false }
if (!checkEmail()){ return false }
if (!checkPhone(phone_field)){ return false }
if (!checkAccountStatus()){ return false }
if (!checkComments()){ return false }

return true
}//end form_validation()

You can clean it up even more by replacing the variables with the
document.getElementById(...) in each function call.

Paul

__._,_.___
.

__,_._,___
[1-3]

about | contact  Other archives ( Real Estate discussion Medical topics )