Skip to content

Instantly share code, notes, and snippets.

@pinceladasdaweb
Created May 20, 2013 15:31
Show Gist options
  • Save pinceladasdaweb/5612973 to your computer and use it in GitHub Desktop.
Save pinceladasdaweb/5612973 to your computer and use it in GitHub Desktop.
Restricting File Type Before Uploading with JavaScript
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Restricting File Type Before Uploading with JavaScript</title>
</head>
<body>
<input type="file" name="upload" id="upload">
<script>
var addEvent = (function () {
var setListener = function (el, ev, fn) {
if (el.addEventListener) {
el.addEventListener(ev, fn, false);
setListener = function (el, ev, fn) {
el.addEventListener(ev, fn, false);
};
} else if (el.attachEvent) {
el.attachEvent('on' + ev, fn);
setListener = function (el, ev, fn) {
el.attachEvent('on' + ev, fn);
};
} else {
el['on' + ev] = fn;
setListener = function (el, ev, fn) {
el['on' + ev] = fn;
};
}
};
return function (el, ev, fn) {
setListener(el, ev, fn);
};
}());
var upload = document.getElementById('upload');
addEvent(upload, 'change', function(){
if (/.*(\.jpg|\.gif|\.png)$/i.test(this.value)){
alert('Ok, this extension is allowed');
} else {
alert('Please only upload files that end in types: \n\n .jpg, .gif or .png');
this.value = '';
}
})
</script>
</body>
</html>
@wbruno
Copy link

wbruno commented Sep 30, 2013

Muito bom!
Só troca:

return function (el, ev, fn) {
    setListener(el, ev, fn);
};

por

    return setListener;

=D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment