-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?

5
  • developer.mozilla.org/en-US/docs/Web/HTML/Element/… for modern browsers, will only need the js version for IE < 10 Commented Jun 15, 2015 at 18:35
  • read this : stackoverflow.com/questions/4328947/… Commented Jun 15, 2015 at 18:38
  • Wow, do I feel dumb... Total brainfart. Thank you so much! Commented Jun 15, 2015 at 18:40
  • I don't think document.getElementById("uploadFile").value = this.value; will work, by the way. Commented Jun 15, 2015 at 18:40
  • @TRose Hey i have your solution Commented Jun 15, 2015 at 18:49

1 Answer 1

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.");
    }
};
Sign up to request clarification or add additional context in comments.

1 Comment

Had a brainfart, and forgot to explore the accept attribute. My question is now moot, though this is also extremely helpful. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.