Advertisement
Guest User

file upoload javascript and jquery validation

a guest
Jul 11th, 2011
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*First you need this in your html */
  2.  <fieldset class="images">            
  3.     <input type="file" name="imagenupload1" id="imagenupload1" tabindex="25" />
  4. </fieldset>
  5.  
  6.  
  7.  
  8.  
  9. /*Now in your javascript file*/
  10. /*First we define some variables*/
  11. var validar_imagenupload=new Boolean(false);
  12. var validar_imagenextension=new Boolean(false);
  13. /* This are the valid extensions. Add or remove as you wish */
  14. var extensiones_permitidas = new Array(".gif", ".jpg", ".jpeg", ".png");   
  15.  
  16.  
  17.     /* Now, the image upload validation */
  18.     $('#imagenupload1').change(function(){
  19.         validar_imagenupload=false;
  20.         validar_imagenextension = false;   
  21.         var node = document.getElementById('imagenupload1');
  22.         var check = node.files[0].fileSize;
  23.         var nombreImg =  node.files[0].fileName;
  24.         var extension = (nombreImg.substring(nombreImg.lastIndexOf("."))).toLowerCase();
  25.  
  26.         /* check for maximum size. In this case is 300KB. You can set to whatever you want  */
  27.         if (check < 300001){
  28.             //Size is OK
  29.             /* Check file extension */
  30.             for (var i = 0; i < extensiones_permitidas.length; i++) {
  31.                 if (extensiones_permitidas[i] == extension) {
  32.                     validar_imagenupload = true;
  33.                     validar_imagenextension = true;
  34.                     break;
  35.                 } else{
  36.                     validar_imagenextension = false;
  37.                 }
  38.             }
  39.        
  40.         } else{
  41.             alert('File is too big');
  42.             clearFileUpload('imagenupload1');
  43.             validar_imagenextension = true;
  44.         }
  45.         if (validar_imagenextension == false){
  46.             alert('File is not an image');
  47.             clearFileUpload('imagenupload1');  
  48.         }
  49.        
  50.     });
  51.  
  52.  
  53.  
  54.  
  55. /* We also need this function */
  56. function clearFileUpload(id){
  57.     // get the file upload element
  58.     fileField = document.getElementById(id);
  59.     // get the file upload parent element
  60.     parentNod = fileField.parentNode;
  61.     // create new element
  62.     tmpForm = document.createElement("form");
  63.     parentNod.replaceChild(tmpForm,fileField);
  64.     tmpForm.appendChild(fileField);
  65.     tmpForm.reset();
  66.     parentNod.replaceChild(fileField,tmpForm);
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement