Preventing form submission not working

Therefore, I am trying to prevent the form from being submitted 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 does not work. The request simply passes despite the fact that it performs the preventDefault and stopPropagation functions.

However, if I do the following, it will successfully prevent sending:

$("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 a handler at the document level, and the latter to the form itself. By the way, I use form_foran assistant to render the form.

0
source share
1 answer

Try using Regular Expressions to validate your user input. An 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;
    }
}
0

All Articles