View Full Version : javascript validation for only particular image formats

08-30-2004, 07:44 AM
HI all im santosh
new to the javascript
i need a validation code which takes only the image formats like jpeg,gif,jpg etc .
That is when i click on browse and try to save the file which is in any other format other than that i mentioned above i should get an alert message
please help me out
thanx in advance

Willy Duitt
08-30-2004, 09:12 AM
Your question is not very clear...
What do you mean Browse too and then Save?
I would assume if they could browse to it... it has already been saved...

But you can try something like this to check if the file which was browsed to is indeed an image...

<title>File System Object Image Check</title>
<script type="text/javascript">
function getFile(file){
var fObj = new ActiveXObject("Scripting.FileSystemObject");
var form = document.forms['form'];

var image = new Image();
image.src = file;
form.size.value = fObj.GetFile(file).Size+' Bytes';
form.type.value = fObj.GetFile(file).Type;
form.width.value = image.width+' px';
form.height.value = image.height+' px';

for(var i=0; i<form.elements.length; i++){
form.elements[i].value = '';
} alert('Please choose an image!!');

<b>Select an Image File to check:</b>
<form name="form">
<input type="file" name="file" onchange="getFile(this.value)"><br>
<input type="text" name="size"> : SIZE<br>
<input type="text" name="type"> : TYPE<br>
<input type="text" name="width"> : WIDTH<br>
<input type="text" name="height"> : HEIGHT<br>


08-30-2004, 10:14 AM
Maybe he meant that if the user chooses a non-image file and clicks the Save button to submit the page, an alert will show.

<script type="text/javascript">
function validate(oForm){
if (!/(\.(gif|jpg|jpeg|bmp|png))$/i.test(oForm.file1.value)){
alert("Please attach an image.");
return false;
return true;
<form name="uploadForm" action="upload.php" method="post" enctype="multipart/form-data" onsubmit="return validate(this)" />
<input type="file" name="file1" />
<input type="submit" value="Save" />

NOTE: Don't forget to always validate on the server-side as javascript can be disabled or bypassed.