0

So I'm trying to prevent form submit if the input is empty. The code looks something like this:

$(document).on("submit", "form#input_form", function(e){
  if(!$(this).find("input[type=text]").val()){
    e.preventDefault();
    e.stopPropagation();
  }
});

This doesn't work. The request just goes through even though it executes both preventDefault and stopPropagation.

However, if I do the following it successfully prevents submit:

$("form#input_form").on("submit", function(e){
  if(!$(this).find("input[type=text]").val()){
    e.preventDefault();
    e.stopPropagation();
  }
});

I don't understand what the difference is, it's basically the same thing except that the former attaches the handler at document level whereas the latter does it to the form itself. By the way, I'm using form_for helper to render the form.

Vlad
  • 7,419
  • 11
  • 51
  • 82

1 Answers1

0

Try using Regular Expressions to validate your user's input. Example shown below:

var userInputVal = $(this).find("input[type=text]").val();

// validate the user input. no error if user entered data with one or more characters.
function validateUserInput() {
    var n = /(\.){1,}/; // creates a regular expression object pattern.
    if (n.test(userInputVal)) {  
        userInputError.hide(); // hide the error message if the user input is one or more characters
        return true;
    } else {
        userInputError.show(); // show the error message if the user input is one or more characters
        return false;
    }
}
Luke Schoen
  • 3,418
  • 2
  • 21
  • 20