Checking for attachments in JavaScript

Jake Howlett, 5 December 2000

Category: JavaScript; Keywords: attachment upload limit

Have you ever needed to validate a form and check that there is at least one attachment? I did this recently and came up with the following solution.

Place the following Formula in to the HTML Header, $$HTMLHead field or in to a Computed Text hotspot.

"<script type=\"text/javascript\">"+@NewLine+
" var numOfAttachments = " + @Text(@Attachments) + ";"+@NewLine+
"</script>"


This will produce the following HTML in a document that has one attachment.

<script type="text/javascript">
var numOfAttachments = 1;
</script>


This number variable it global as it is defined outside of any functions. This means that it can be used in ANY of your JavaScript functions on that page. Consider the following function that is called before the form can be submitted:

function validate( frm ){
//only validate your upload if there are no attachments already...
if ( numOfAttachments == 0 ) {
if ( frm.nameOfUpload.value == '' ) {
alert('You need to upload at least one file');
frm.nameOfUpload.focus();
return false;
}
return true;
}


If you don't know the name of your upload control (none R5 users!) then consider using this method to get a handle on it.

Note: This method is not perfect!! If you have an attachment on a document and the user has marked it for deletion using the check box at the bottom, the validation function will not check for a new upload and the document will then have NO attachments.

To get around this consider adding the following line to the function which checks to see if they have checked the text box. This takes account of the fact that the delete attachments check boxes will always be the last elements on the document:

if(numOfAttachments == 0 || (numOfAttachments ==1 && frm.elements[frm.elements.length-1].checked)){