Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Form validation for file extension upload

Status
Not open for further replies.

techskool

Technical User
Jun 20, 2002
151
GB
Im a total incompetent when it comes to JavaScript as i work soley in ASP and SQL, but against my better judgement tried some client side form validation the other day.

I wrote and hacked this together but it falls over.

Can you tell me whats up with it?

Thanks

Dave

function onSubmitForm() {
if (document.frmSend.attach.value == "")
alert("Please press the browse button and pick a file.")
else if (document.frmSend.attach.value != "")

{
var ext = document.frmSend.attach.value;
var VARext = new Array("doc","xls","ppt","PDF");
ext = ext.substring(ext.length-3,ext.length);
ext = ext.toLowerCase();
for (i = 0;i < VARext.length;i++)
{
if (ext == VARext)
return true;
else
alert('You selected a .'+ext+' file; please select a valid file instead!');
return false;
}
}

}
 

Hard to "fix" when you haven't said what's wrong. I haven't tested it, but try this instead:

Code:
function onSubmitForm() {
	var formObj = document.forms['frmSend'];
	var ext = formObj.attach.value;
	if (ext == '')
		alert('Please press the browse button and pick a file.');
	else {
		var VARext = ['doc', 'xls', 'ppt', 'PDF'];
		ext = ext.substring(ext.length-3, ext.length).toLowerCase();
		for (var i=0; i<VARext.length; i++) {
			if (ext == VARext[i])
				return (true);
			else {
				alert('You selected a .' + ext + ' file; please select a valid file instead!');
				return (false);
			}
		}
	}
}

I added a missing set of braces around the last if/else set, and restructured some of the code. Also, the most common error is using "document.fornName", which works in IE, but not much else (and isn't DOM "compliant", anyway).

Hope this helps,
Dan
 
this logic seems wrong:

Code:
for (i = 0;i < VARext.length;i++)
{
 if (ext == VARext[i])
  return true;
 else
  alert('You selected a .'+ext+' file; please select a valid file instead!');
 return false;
}

try something like

Code:
var x = false
for (i = 0;i < VARext.length;i++)
{
 if (ext == VARext[i])
  x = true;
}

if(!x)
 alert('You selected a .'+ext+' file; please select a valid file instead!');

return x;

hth

simon



 
That ideal

any thanks for all the help guys.

Dave
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top