I am working on Visualforce Site. I am using to attach the attachment in contact. I want to restrict the user to attach only image, PDF or .jpg file at client side. How can I do this using jquery?

Here are my inputfile fields:

<apex:inputFile id="atchmntA" value="{!attachment1.body}" filename="{!attachment1.name}" title="Please select the files to upload"/>

<apex:inputFile id="atchmntB" value="{!attachment2.body}" filename="{!attachment2.name}" title="Please select the files to upload"/>

On save button I am already calling a javascript function in which I can add the code to restrict user to upload certain kind of files only. Please help!!

Thanks you in advance!!


The following JavaScript function can be used to validate that the type of file that a user tries to upload is of a certain format. It does this by checking that the files extention (eg .jpg) is in an array of allowed extensions that is passed to the function as an argument.

VF Page

<apex:page standardController="Document" extensions="documentExt">
  <script type="text/javascript">
    function TestFileType(elemid,fileName, fileTypes) {
        if (!fileName) return;
        dots = fileName.split(".")
        //get the part AFTER the LAST period.
        //fileType = "." + dots[dots.length - 1]; We don't need this
        //if(fileTypes.join(".").indexOf(fileType) != -1){
        if(fileTypes.indexOf(fileType) != -1){   //We don't need to add .
            //alert('That file is OK!');
            alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
            document.getElementById(elemid).value = "";
  <apex:inputFile onchange="TestFileType(this.id,this.value, ['gif', 'jpg', 'png', 'jpeg', 'pdf']);" id="atchmntA" value="{!document.body}" filename="{!document.name}" title="Please select the files to upload"/>


/*** Controller ***/
public class documentExt {
    public documentExt(ApexPages.StandardController controller) {
        Document d = (Document) controller.getRecord();
        d.folderid = UserInfo.getUserId(); //this puts it in My Personal Documents
  • It is working perfectly fine. Awesome code. Thanks. May 26 '16 at 10:26

Yes, you can. Try something like this:

if($("#atchmnt").filename != ".pdf" || $("#atchmnt").filename != ".jpg")
   alert("you can only upload pdf or jpg files");
   alert("Error: you cannot upload this file.")

Obviously, you have edit the action in the if and else body.

  • $("#atchmntA").filename is returning 'undefined'. May 26 '16 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.