Problem when validating field 'file'

1

I took a function here from the Internet to try to validate my 'file' field, which will be for the client to send photos, I want the client can not leave the 'file' field empty, without uploading any, and I want it to be of at most 300mb, and that is in the format either 'jpeg' or 'jpg' or 'png'. I just got a code to validate if it is bigger than 300MB, I just do not know if it's totally right, this:

function validafoto() {
var upload = document.cad.getElementById("upload");
    var size = upload.files[0].size;
    if(size > 3145728) { //3MB         

      alert('Não permitido'); //Acima do limite
     return false;

}

And now I do not know how to call it in my form, I tried on my function validate form, but it did not work very well, could they help? I'll leave the entire code on my form here: link

    
asked by anonymous 11.06.2018 / 01:54

1 answer

1

The function is correct in the part of checking the weight of the file, there is only one error in this method: document.cad.getElementById("upload"); , where cad is the id of the form and does not fit in this way in the method. It would have to be document.getElementById("upload"); .

To find out if the field is empty, you can use this if before taking the size of the query:

if(!upload.value){
   alert('Selecione um arquivo');
   return false;
}

To check the type (extension), this would be if :

var tipo = upload.value.split(".").pop();          // pego a extensão do arquivo
var valida_tipo = tipo.match(/^(jpeg|jpg|png)$/i); // verifico se é jpeg, jpg ou png
if(!valida_tipo){
   alert('Tipo não permitido');
   return false;
}

The full function would look like this:

function validafoto() {
   var upload = document.getElementById("upload");
   if(!upload.value){
      alert('Selecione um arquivo');
      return false;
   }

   var tipo = upload.value.split(".").pop();
   var valida_tipo = tipo.match(/^(jpeg|jpg|png)$/i);
   if(!valida_tipo){
      alert('Tipo não permitido');
      return false;
   }

   var size = upload.files[0].size;
   if(size > 3145728) { //3MB         
      alert('Não permitido'); //Acima do limite
      return false;
   }

   return true;
}

To validate from another function, just call if(!validafoto()) return; .

    
11.06.2018 / 02:33