JavaScript Form Validation

kbjradmin

New Member
Messages
512
Reaction score
2
Points
0
i am working on a site for my web developement class and am having some trouble with validating the contents of a form. the page i'm having trouble on is at http://cs.clark.edu/~jbrum4030/ctec122/final/order.htm

(before anyone says anything, no, none of this works in IE, but the instructor doesn't care about IE, so for the time being, neither do i. and if you're using IE, don't.)

here is the validation script i have so far...

Code:
function checkForm(type,id)
{
	
	if ( id == 'all')
	{
		requiredFields = document.getElementsByClassName('required-done');
		for ( var i in requiredFields )
		{
			requiredFields[i].setAttribute('class', 'required');
		}
	}
	
	switch(type)
	{
	
		case 'text':
			if ( textField(id) )
			{
				document.getElementById(id + '-required').setAttribute('class', 'required-done');
			}
			else
			{
				document.getElementById(id + '-required').setAttribute('class', 'required');
			}
			break;
			
		case 'num':
			if ( numField(id) )
			{
				document.getElementById(id + '-required').setAttribute('class', 'required-done');
			}
			else
			{
				document.getElementById(id + '-required').setAttribute('class', 'required');
			}
			break;
			
		case 'digit':
			if ( digitField(id) )
			{
				document.getElementById(id + '-required').setAttribute('class', 'required-done');
			}
			else
			{
				document.getElementById(id + '-required').setAttribute('class', 'required');
			}
			break;
			
		case 'address':
			if ( addressField(id) )
			{
				document.getElementById(id + '-required').setAttribute('class', 'required-done');
			}
			else
			{
				document.getElementById(id + '-required').setAttribute('class', 'required');
			}
			break;
			
		case 'citySZ':
			if ( textField(id[0]) && document.getElementById(id[1]) && numField(id[2]) )
			{
				document.getElementById('citySZ-required').setAttribute('class', 'required-done');
			}
			else
			{
				document.getElementById('citySZ-required').setAttribute('class', 'required');
			}
			break;
			
		case 'phone':
			if ( digitField(id[0],3) && digitField(id[1],3) && digitField(id[2],4) )
			{
				document.getElementById('phone-required').setAttribute('class', 'required-done');
			}
			else
			{
				document.getElementById('phone-required').setAttribute('class', 'required');
			}
			break;
			
		case 'email':
			if ( emailField(id) )
			{
				document.getElementById(id + '-required').setAttribute('class', 'required-done');
			}
			else
			{
				document.getElementById(id + '-required').setAttribute('class', 'required');
			}
			break;
			
		default:
			// code here
			break;
			
	}
	
}

function textField(id,value)
{
	if ( value )
	{
		var value = value;
	}
	else
	{
		if ( id instanceof Array )
		{
			for ( i in id )
			{
				var value = document.getElementById(id[i]).value;
				if ( value != null && value != '' )
				{
					return true;
				}
				else
				{
					return false;
				}
			}
		}
		else
		{
			var value = document.getElementById(id).value;
			if ( value != null && value != '' )
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
}

function numField(id,value)
{
	if ( value )
	{
		var value = value;
	}
	else
	{
		var value = document.getElementById(id).value;
	}
	if ( isNaN( value ) )
	{
		return false;
	}
	else if ( value == null || value == '' )
	{
		return false;
	}
	else
	{
		return true;
	}
}

function digitField(id,len,value)
{
	if ( value )
	{
		var value = value;
	}
	else
	{
		var value = document.getElementById(id).value;
	}
	len = len || 'any';
	if ( value.match(/^\d+$/) )
	{
		if ( value.length == len || len == 'any' )
		{
			return true;
		}
	}
	return false;	
}

function emailField(id,value)
{
	if ( value )
	{
		var str = value;
	}
	else
	{
		var str = document.getElementById(id).value;
	}
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1)
	{
	   return false;
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
	{
	   return false;
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
	{
	   return false;
	}
	if (str.indexOf(at,(lat+1))!=-1)
	{
	    return false;
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
	{
	    return false;
	}
	if (str.indexOf(dot,(lat+2))==-1)
	{
	    return false;
	}
	if (str.indexOf(" ")!=-1)
	{
	    return false;
	}
	return true;			
}

function addressField(id,value)
{
	if ( value )
	{
		var address = value;
	}
	else
	{
		var address = document.getElementById(id).value;
	}
	var addressArray = address.split(' ');
	if ( address && addressArray[0] && addressArray[1] && addressArray[2] && addressArray[3] )
	{
		if (
			digitField(null,'any',addressArray[0]) &&
			addressArray[1] in new Array( 'n','s','e','w','ne','nw','se','sw' ) &&
			textField(null,addressArray[2]) &&
			textField(null,addressArray[3])
		)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;	
	}
}

function checkNumSuffix(value)
{
	if ( ! value ) { return false; }
	var len = value.length;
	var suffix = value[len-2] + value[len-1];
	if ( digitField(null,null,value.substring(0,len-2)) )
	{
		if ( suffix in new Array( 'st', 'nd', 'rd', 'th' ) )
		{
			return suffix;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

everything works except the address field, the city/state/zip-code field, and the phone number field.

please help!



edit:
i got phone to work, but the other two still don't.
 
Last edited:

fguy64

New Member
Messages
218
Reaction score
0
Points
0
are you saying you changed the code from what is shown above to make phone work? What change did you make?

Also, what do you mean by "doesn't work"? The code doesn't execute? or it executes but does not do what you want?

It would help if you told us what is supposed to happen, what makes an address or a city/state valid or invalid, rather than us trying to figure it out from code that is probably wrong in the first place.
 

pythondev

New Member
Messages
59
Reaction score
0
Points
0
well after a bit of fiddling I came up with a few issues

Code:
<script type="text/javascript">
<!--

var indent = "\t\t\t\t\t\t\t";
var stateList = new Array("","AK","AL","AR","AS","AZ","CA","CO","CT","DC","DE","FL","GA","GU","HI",
    "IA","ID","IL","IN","KS","KY","LA","MA","MD","ME","MH","MI","MN","MO","MS","MT","NC","ND","NE",
    "NH","NJ","NM","NV","NY","OH","OK","OR","PA","PR","PW","RI","SC","SD","TN","TX","UT","VA","VI",
    "VT","WA","WI","WV","WY");

document.write( indent + "<select id=\"states\" onchange=\"checkForm('citySZ',new Array('city','state','zip'));\">\n" );

for ( var state in stateList )
{
    document.write( indent + "\t<option value=\"" + stateList[state] + "\">" + stateList[state] +
        "</option>\n" );
}

document.write ( indent + "</select>" );

//-->
</script>
I think you might want to use id "state" for the "select id=\"states\""

also, I have no idea what your trying to validate in the address in

Code:
if (
digitField(null,'any',addressArray[0]) &&
addressArray[1] in new Array( 'n','s','e','w','ne','nw','se','sw' ) &&
textField(null,addressArray[2]) &&
textField(null,addressArray[3])
)
But everything after the first digitField wont validate.
and even that wouldn't work with my old apartment 18N10F (thats the Block 18, North tower, level 10, apartment F)
for example...
 
Last edited:

kbjradmin

New Member
Messages
512
Reaction score
2
Points
0
first, thank you both of you for your replies.

@fguy64, i already changed the code displayed to show the changes.

@pythondev, the city/state/zip-code part works now, thanks for finding that.
i didn't even think about the possibility of letters in the street address, i can change that, but even so, i can't get the script to work.
 

kbjradmin

New Member
Messages
512
Reaction score
2
Points
0
@freecrm, thank you for the link, i will probably use that on future site, but for the moment, i would really like to get this to work.
 

pythondev

New Member
Messages
59
Reaction score
0
Points
0
for debugging just use the alert function in javascript to pop up the data on false, thats what I did with it.

there are much simpler ways of doing it in javascript for validating a street address.
can explode everything with the split then just run the array into a loop.
Look for digits in array[0] then in another array put the array(ave, st, lane, etc) and look for match with that.

even with that, still difficult to validate an address properly as I routinely give wrong address on certain sites for software download etc :p (123 sesame st, is a popular one :p) unless you want to validate against a live database street directory.
 

kbjradmin

New Member
Messages
512
Reaction score
2
Points
0
alright, so i decided to start over on the main address validation seeing as people had brought out some good points, and it turns out that there are a LOT of different street suffixes (st, ave, lane, blvd, etc.). so, in case anyone ever needs this other than me, i put together an array of values for these.

Code:
var streetSuffix = Array( 'aly', 'anx', 'arc', 'ave', 'byu', 'bch', 'bnd', 'blf', 'blfs',
    'btm', 'blvd', 'br', 'brg', 'brk', 'brks', 'bg', 'bgs', 'byp', 'cp',
    'cyn', 'cpe', 'cswy', 'ctr', 'ctrs', 'cir', 'cirs', 'clf', 'clfs',
    'clb', 'cmn', 'cor', 'cors', 'crse', 'ct', 'cts', 'cv', 'cvs', 'crk',
    'cres', 'crst', 'xing', 'xrd', 'curv', 'dl', 'dm', 'dv', 'dr', 'drs',
    'est', 'ests', 'expy', 'ext', 'exts', 'fall', 'fls', 'fry', 'fld',
    'flds', 'flt', 'flts', 'frd', 'frds', 'frst', 'frg', 'frgs', 'frk',
    'frks', 'ft', 'fwy', 'gdn', 'gdns', 'gtwy', 'gln', 'glns', 'grn',
    'grns', 'grv', 'grvs', 'hbr', 'hbrs', 'hvn', 'hts', 'hwy', 'hl', 'hls',
    'holw', 'inlt', 'is', 'iss', 'isle', 'jct', 'jcts', 'ky', 'kys', 'knl',
    'knls', 'lk', 'lks', 'land', 'lndg', 'ln', 'lgt', 'lgts', 'lf', 'lck',
    'lcks', 'ldg', 'loop', 'mall', 'mnr', 'mnrs', 'mdw', 'mdws', 'ml', 'mls',
    'msn', 'mtwy', 'mt', 'mtn', 'mtns', 'nck', 'orch', 'oval', 'opas', 'park',
    'pkwy', 'pass', 'psge', 'path', 'pike', 'pne', 'pnes', 'pl', 'pln', 'plns',
    'plz', 'pt', 'pts', 'prt', 'prts', 'pr', 'radl', 'ramp', 'rnch', 'rpd',
    'rpds', 'rst', 'rdg', 'rdgs', 'riv', 'rd', 'rds', 'rte', 'row', 'rue',
    'run', 'shl', 'shls', 'shr', 'shrs', 'skwy', 'spg', 'spgs', 'spur', 'sq',
    'sqs', 'sta', 'stra', 'strm', 'st', 'sts', 'smt', 'ter', 'trwy', 'trce',
    'trak', 'trfy', 'trl', 'tunl', 'tpke', 'upas', 'un', 'uns', 'vly', 'vlys',
    'via', 'vw', 'vws', 'vlg', 'vlgs', 'vl', 'vis', 'walk', 'way', 'ways',
    'wl', 'wls' );

and, yes, this is a complete list, i took it from the US Postal Service website.
 
Top