user984621
user984621

Reputation: 48483

Javascript - how to correctly verify form data?

I have a form with a few text inputs and also with one file-type input, in which I attempt to verify, if the selected file is PDF. I am doing that this way:

$("#myform").bind("submit", function() {
    var ext = $('#file_input').val().split('.').pop().toLowerCase();
    if($.inArray(ext, ['pdf']) == -1) {
        alert('ERROR!');
    }
});

But in the part of code above is one lack - if all inputs except the file-input (lets sat the file is DOC) are valid (=> file-input is not valid) and I click on the SUBMIT button, then is displayed alert message ERROR!, but the form is sent.

How can I "stop" sending the form, if the file type is not valid?

Upvotes: 0

Views: 107

Answers (4)

Anthony Grist
Anthony Grist

Reputation: 38345

In a jQuery callback function bound to an event you have two options.

You can pass a reference to the event to the anonymous function and call e.preventDefault():

$('#myform').bind('submit', function(e) {
    e.preventDefault();

    // Your code
});

e.preventDefault() prevents the default functionality (in this case, submitting the form).

Or you can return false to both prevent the default functionality and prevent the event from bubbling; the same as calling e.preventDefault(); e.stopPropagation().

Upvotes: 2

Tomer
Tomer

Reputation: 17940

You have 2 ways:

  1. Keep your code as it is and add return false:

    $("#myform").bind("submit", function() {
    var ext = $('#file_input').val().split('.').pop().toLowerCase();
    if($.inArray(ext, ['pdf']) == -1) {
        alert('ERROR!');
        return false;
    }
    });
    
  2. change the function signature to accept the event and use the preventDefault():

     $("#myform").bind("submit", function(e) {       
    var ext = $('#file_input').val().split('.').pop().toLowerCase();
    if($.inArray(ext, ['pdf']) == -1) {         
      alert('ERROR!');
      e.preventDefault();
    }
    });
    

Upvotes: 0

Beat Richartz
Beat Richartz

Reputation: 9622

You can shorten the code by doing this:

if (!(/\.pdf$/i).test($('#file_input').val())) {
  // not valid, do what you like here
  // return false to prevent submit
  return false;

The form is prevented from submitting by returning false; preventDefault on the form submit event is not working in IE 7/8, return false does the job.

Upvotes: 2

Chandu
Chandu

Reputation: 82933

Try this:

$("#myform").bind("submit", function(e) {
    var ext = $('#file_input').val().split('.').pop().toLowerCase();
    if($.inArray(ext, ['pdf']) == -1) {
      e.preventDefault(); //Prevents the default action which is form submit
      alert('ERROR!');
    }
});

Upvotes: 2

Related Questions