Skip to content

Instantly share code, notes, and snippets.

@keenahn
Created December 3, 2012 21:29
Show Gist options
  • Save keenahn/4198250 to your computer and use it in GitHub Desktop.
Save keenahn/4198250 to your computer and use it in GitHub Desktop.
JS: File upload validation
// Just some examples of how to do file validation with javascript
// IS NOT BULLETPROOF and should be coupled with server side validation
// But, it can help
var file = this.fileInput.files[0];
if ('name' in file) {
name = file.name
} else {
name = file.fileName
}
if ('size' in file) {
size = file.size
} else {
size = file.fileSize
}
if (!file || !file.type.match(/image.*/)) {
this.onError("Only image files can be uploaded");
return;
} else if(size && size > 5242880){
this.onError("Please choose a file of size 5MB or smaller");
return;
} else if(name && name){
ext = name.substr(name.lastIndexOf('.') + 1).toLowerCase()
if(ext != "jpg" && ext != "gif" && ext != "png" && ext != "jpeg") {
this.onError("Please choose an image of type 'jpeg', 'jpg', 'png', or 'gif'");
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment