Rosamunda Rosamunda - 2 months ago 9
Javascript Question

How to validate with jQuery that the user is uploading a file using an HTML form?

I want to validate that the user won't leave a file input field enpty.

I'm using the jQuery plugin validation. In that link there's a demo of how the plugin is supposed to work.

I've added the files into the footer of my page (and checked that they are in fact there):

<!-- jQuery y Bootstrap minificados -->
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<!-- validacion de los campos de los formularios -->
<script src="/js/validate/jquery.validate.min.js"></script>
<script src="/js/validate/additional-methods.min.js"></script>
<!-- My file -->
<script src="/js/formularios.js"></script>


In my formularios.js file I've added this:

//validación de la data en el formulario de carga de documentación
$().ready(function {

$("#cargarDoc").validate({
rules: {
dni: {
required: true,
extension: "gif|jpeg|jpg|png"
},
messages:{
dni: {
required: "No puedes dejar este campo en blanco",
extension: "Solamente puedes cargar archivos del tipo: gif, jpeg, jpg o png"
}
}
}
})
})


And here is my HTML form:

<form id="cargarDoc" method="POST" action ="cargarDoc.php" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<div class="form-group">
<label for="dni">Cargá acá tu DNI</label>
<input type="file" id="dni" name="dni">
</div>
<button type="submit">Cargar Documentación</button>
</form>


Now, when I submit the form, even empty, it does let me. What am I doing wrong?

Answer

The issue is a syntax error, probably caused by bad indentation of the code.

/validación de la data en el formulario de carga de documentación
$().ready(function {

  $("#cargarDoc").validate({
        rules: {
            dni: {
                required: true,
                extension: "gif|jpeg|jpg|png"
            }
        },
        messages:{
            dni: {
                required: "No puedes dejar este campo en blanco",
                extension: "Solamente puedes cargar archivos del tipo: gif, jpeg, jpg o png"
            }
        }
    });
});

Compare the code above with your code to see the subtile difference.

Validate uses objects to define its behavior.

"rules", "message" and "dni" are objects.
An object is defined in between curly braces: { and }, and is formed of key and value pairs.

An object can include other objects...
This is the case of "rules" and "message" that both include their own "dni" object.

A coma , within an object, is used as a separator.

A semicolon ; is used to separate statements in many coding languages.