Created
December 3, 2012 21:29
-
-
Save keenahn/4198250 to your computer and use it in GitHub Desktop.
JS: File upload validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
validate_file = -> | |
file = @fileInput.files[0] | |
if "name" of file | |
name = file.name | |
else | |
name = file.fileName | |
if "size" of file | |
size = file.size | |
else | |
size = file.fileSize | |
if not file or not file.type.match(/image.*/) | |
alert "Only image files can be uploaded" | |
return | |
else if size and size > 5242880 | |
alert "Please choose a file of size 5MB or smaller" | |
return | |
else if name | |
ext = name.substr(name.lastIndexOf(".") + 1).toLowerCase() | |
if ext isnt "jpg" and ext isnt "gif" and ext isnt "png" and ext isnt "jpeg" | |
alert "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