validate form with image if the field is empty?

1

When the input of the image is empty and I send it my javascript does not run but when I attach a doc it tells me that I have to attach a valid image which is fine. Then I would need my if I recognized the empty field to show that alert. I tried with null , undefined and " " within the if, maybe I did something wrong.

I place only the code fragment of the image

function validar(){
    
    var c =true;
    var o = document.getElementById('archivo');
    var uploadFile = o.files[0];
    if (!(/\.(jpg|png|gif)$/i).test(uploadFile.name) ) {
        alert('Ingrese un archivo con alguna de las siguientes extensiones .jpeg/.jpg/.png/.gif ');
        c= false;
    }
     return c;
    }
<form action="" method="POST" enctype="multipart/form-data" onSubmit="return validar()">
  <input type="file" name="archivo" id="archivo" />
  <button>Ok</button>
</form>

 
    
    
asked by MSL 15.03.2018 в 06:37
source

1 answer

2

I would simply check that a file has been attached, using your code something like:

if (o.files.length==0 || !(/\.(jpg|png|gif)$/i).test(uploadFile.name) )
    
answered by 15.03.2018 / 09:23
source