function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ven 777Ven 777 

client-side validation for apex:inputfile field

I am looking to do javascript client-side validation for apex:inputfile field on a visualforce page to check for

1. Required

2. File-size.

Was wondering if there is a code sample or some documentation on the same. Really appreciate any help on the same.

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

Most, if not all, browsers won't give you access to this field, as you could then find out the name of the file and its location.  You have to do things server side with this I'm afraid.

All Answers

bob_buzzardbob_buzzard

Unfortunately there's very little you can do around the apex:inputfile component  This is rendered as an HTML input with type="file" and browsers have very tight security around this, basically to stop javascript accessing information about the user's filesystem.

Ven 777Ven 777

Thanks for the quick response Bob.

 

Yes, I didn't expect much around file-size validation, but was hoping to be able to do the 'required' field validation atleast in the same standard way by getting the handle to the element through -

document.getElementsByName('{!$Component.uploadform.chooseFile}')

 But looks like apex:input generates HTML with a <span> tag around the type="file" field with that  j_id0:uploadform.chooseFile id, and the id for input element is

j_id0:uploadform:chooseFileRPM:inputFile:file. Now I am not sure how to get an handle to this field - j_id0:uploadform:chooseFileRPM:inputFile:file ??

bob_buzzardbob_buzzard

Most, if not all, browsers won't give you access to this field, as you could then find out the name of the file and its location.  You have to do things server side with this I'm afraid.

This was selected as the best answer
Ven 777Ven 777

Was able to handle this server-side as below. This will display this message back on the page:

Error:This file exceeds the maximum size limit of 5MB.

   

public PageReference saveForm() {
        
        if(ApexPages.hasMessages(ApexPages.severity.ERROR)) {
            System.debug('Exceeds File Size limit, abort processing. ApexPages.getMessages() ' + ApexPages.getMessages());            
            return null;
        }

       ......

      ..  actual file processing logic here...

}