April 24, 2009

Allow only selected filetype in attachment using javascript

This code in javascript checks the attachment type,

You can add this code in javascript validation on form submit event to upload only specific file types,

if(document.formname.fieldname.value != "") {
MyFile = document.formname.fieldname.value /* replace with the correct value */
FileArray = MyFile.split("\\")
FileName = FileArray[FileArray.length-1]
ExtArray = FileName.split(".")
Ext = ExtArray[ExtArray.length-1]
Ext = Ext.toUpperCase(Ext)

if(!(Ext=="DOCX" || Ext=="DOC" || Ext=="TXT" || Ext=="PDF" || Ext=="RTF"))
{
alert("Invalid Upload File! Upload doc or txt or pdf or rtf file only")
return false
}
}

Explanation of the code:

The selected file for attachment is assigned to the variable "MyFile". With the build-in javascript split() the filename and the file extensions are splitted. To allow browser compatible converting the file extension to uppercase using "toUpperCase" function. When the if condition satisfied "return false" to terminate the form submission.

No comments:

Post a Comment