-1

I have essentially re-skinned a file-upload form field.

<input id="uploadFile" placeholder="Choose File" disabled="disabled" />
<div class="fileUpload btn btn-primary">
    <span>Upload</span>
    <input id="uploadBtn" type="file" class="upload" />
</div>

.fileUpload {
    position: relative;
    overflow: hidden;
    margin: 10px;
}
.fileUpload input.upload {
    position: absolute;
    top: 0;
    right: 0;
    margin: 0;
    padding: 0;
    font-size: 20px;
    cursor: pointer;
    opacity: 0;
    filter: alpha(opacity=0);
}

I couldn't get the name of the selected file to display with vanilla CSS so this project became a little more complicated.

document.getElementById("uploadBtn").onchange = function () {
    document.getElementById("uploadFile").value = this.value;
};

Here's the JSFiddle.

http://jsfiddle.net/ccsGK/1532/

Good progress so far, but I need client-side validation of the file that is selected for upload.

Ex: I only want to allow .pdf or .docx extensions. Is there a way to clear the file upload field if the selected file doesn't match that extension? And maybe add an alert to let the person know their file was cleared or not the right format?

TRose
  • 1,718
  • 1
  • 16
  • 32

1 Answers1

1

You can simply use a regex to check if it has that extension. If yes, do whatever (add the value to your disabled field). If no, do whatever (cancel the upload, show an alert).

document.getElementById("uploadBtn").onchange = function () {
    if (this.value.match(/\.(pdf|docx)$/)) {
        document.getElementById("uploadFile").value = this.value;
    } else {
        this.value = "";
        alert("Must be a PDF or DOCX.");
    }
};
Scimonster
  • 32,893
  • 9
  • 77
  • 89
  • Had a brainfart, and forgot to explore the `accept` attribute. My question is now moot, though this is also extremely helpful. Thank you. – TRose Jun 15 '15 at 18:44