+ Reply to Thread
Results 1 to 8 of 8
Like Tree2Likes
  • 1 Post By freecrm
  • 1 Post By kbjradmin

Thread: JavaScript Form Validation

  1. #1
    kbjradmin's Avatar
    kbjradmin is offline x10 Elder kbjradmin is an unknown quantity at this point
    Join Date
    Feb 2008
    Location
    Washington State, USA
    Posts
    512

    JavaScript Form Validation

    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 by kbjradmin; 06-01-2009 at 09:27 PM.

  2. #2
    fguy64's Avatar
    fguy64 is offline x10 Sophmore fguy64 is an unknown quantity at this point
    Join Date
    Apr 2009
    Posts
    218

    Re: JavaScript Form Validation

    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.

  3. #3
    pythondev is offline x10Hosting Member pythondev is an unknown quantity at this point
    Join Date
    Mar 2009
    Posts
    59

    Re: JavaScript Form Validation

    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 by pythondev; 06-02-2009 at 05:30 AM.

  4. #4
    kbjradmin's Avatar
    kbjradmin is offline x10 Elder kbjradmin is an unknown quantity at this point
    Join Date
    Feb 2008
    Location
    Washington State, USA
    Posts
    512

    Re: JavaScript Form Validation

    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.

  5. #5
    freecrm's Avatar
    freecrm is offline x10 Elder freecrm is an unknown quantity at this point
    Join Date
    May 2008
    Location
    UK
    Posts
    629

    Re: JavaScript Form Validation

    Don't know if this is of any help, but I use Spry validation widgets, which work great across all browsers (and have good visual feedback). It also uses AJAX, rather than having to store field values on submit and post back.

    http://labs.adobe.com/technologies/s...ield_overview/

    Each element can be tweaked pretty easily.
    dinomirt96 likes this.

  6. #6
    kbjradmin's Avatar
    kbjradmin is offline x10 Elder kbjradmin is an unknown quantity at this point
    Join Date
    Feb 2008
    Location
    Washington State, USA
    Posts
    512

    Re: JavaScript Form Validation

    @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.

  7. #7
    pythondev is offline x10Hosting Member pythondev is an unknown quantity at this point
    Join Date
    Mar 2009
    Posts
    59

    Re: JavaScript Form Validation

    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.

  8. #8
    kbjradmin's Avatar
    kbjradmin is offline x10 Elder kbjradmin is an unknown quantity at this point
    Join Date
    Feb 2008
    Location
    Washington State, USA
    Posts
    512

    Re: JavaScript Form Validation

    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.
    karimirt47 likes this.

+ Reply to Thread

Similar Threads

  1. Disabled HTML Form and Javascript
    By kbjradmin in forum Programming Help
    Replies: 2
    Last Post: 02-04-2009, 05:01 PM
  2. Javascript submit to form submit
    By e85andyou in forum Programming Help
    Replies: 2
    Last Post: 11-03-2008, 08:33 AM
  3. Javascript form to PHP
    By driveflexfuel in forum Scripts & 3rd Party Apps
    Replies: 3
    Last Post: 10-28-2008, 11:15 PM
  4. Javascript form to PHP
    By driveflexfuel in forum Programming Help
    Replies: 2
    Last Post: 10-16-2008, 06:25 PM
  5. form validation w/Javascript
    By surreal5335 in forum Programming Help
    Replies: 3
    Last Post: 05-19-2008, 04:25 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
x10hosting free hosting for the masses
dedicated servers