...

View Full Version : error in javascript in form to check file extension



chakytori
05-01-2007, 02:26 PM
Hi, actually there's no error in the code only that is only made to check for one input field and my form has 3 image upload fields, the original is:



<form enctype="multipart/form-data" action="action.php" method="post" onSubmit="if(!this.img1.value.match(/\.jpg$/i)){alert('Must be JPG file');return false};return val(this)">
<input type="file" name="img1">
</form>


This works great but what modifications should have to be able to check multiple file input fields?

thanks a lot.

shyam
05-01-2007, 03:37 PM
put it in a function and iterate through all your file-upload input elements



assuming u have a form like

<form enctype="multipart/form-data" action="action.php" method="post" onSubmit="return validate(this)">
<input type="file" name="img1" />
<input type="file" name="img2" />
..
<input type="file" name="img10" />
</form>

function validate(myForm) {
var count = 10;
var i;
for ( i = 1; i <= count; i++ ) {
if ( !/\.jpg/i.test(myForm['img' + i].value) {
alert('error msg');
return false;
}
}
return true;
}

glenngv
05-01-2007, 03:38 PM
If the input fields are named img1, img2, and img3, then you can use a loop.

function validate(frm){
for (var i=1; i<=3; i++){
if(!frm.elements["img"+i].value.match(/\.jpg$/i)){
alert('Must be JPG file');
return false;
}
}
return val(this);
}

<form enctype="multipart/form-data" action="action.php" method="post" onSubmit="return validate(this);">
<input type="file" name="img1" />
<input type="file" name="img2" />
<input type="file" name="img3" />
</form>

chakytori
05-03-2007, 01:53 AM
thanx a lot, yes all my images were named in that order so the loop worked great, thanks to all.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum