Javascript validation for File uploading format

Upload file can be validate through javascript . By onclick, onchange, onsubmit we can do this validation. File extension can be analyzed  through below coding. You can change the file extension basis on your  requirement.Validation also for submit without any file selection.This javascript validation is simple and useful .

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<script type="text/javascript">

function file_upload()
{
var imgpath = document.getElementById('word').value;
if(imgpath == "")
{
alert("upload your word file");
document.file.word.focus();
return false;
}
else
{
// code to get File Extension..

var arr1 = new Array;
arr1 = imgpath.split("\\");
var len = arr1.length;
var img1 = arr1[len-1];
var filext = img1.substring(img1.lastIndexOf(".")+1);
// Checking Extension
if(filext == "doc" || filext == "docx")
{
alert("File has been upload correctly")
return false;
}
else
{
alert("Invalid File Format Selected");
document.form.word.focus();
return false;
}
}
}
</script>

fileupload.php

Untitled

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<form name="fileupload" onsubmit="return file_upload();">
<table align="center" bgcolor="#8080FF" height="100">
<tr>
<th> Fileupload:</th>
<td> <input type="file" name="word" id="word" > </td>
</tr>
<tr>
<td> <input type="submit" /> </td>
</tr>
</table>
</form>

This alert message for invalid file format

1

This alert message will come when u choose correct file format.

2

 

 

 

About ram

ram kumar has written 7 post in this blog.

Engaged with Web Development

4 Responses to Javascript validation for File uploading format

  1. Gracy says:

    Nice example but what if it will be more then 8 type of extns

  2. wasim says:

    Thanks for your coding.
    How i can redirect to other page. ?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>