0

In my form, the user has to enter 4 values to generate the multiplication table.

To validate the user's input I use jQuery. If the input is not valid (blank, non-integer number, etc) then the error message is displayed. The "Submit" button should only work when the input is valid.

I used this to prevent the form from submitting (source: Preventing a form from submitting in jQuery Validate plugin's submitHandler function):

$("#inputForm").submit(function(generateTable) {
   generateTable.preventDefault();
}).validate({
   //code
});

Here is the validate.js file:

function generateTable() {
   //code
   return false;
}

$(function() {
   $("#inputForm").submit(function(e) {
      e.preventDefault();
   }).validate({
      //rules
      //messages
});

Here is HTML file:

<form id="inputForm" class = 'card p-3 bg-light' class="form-horizontal" onsubmit="return generateTable();">

The issue is that the form is getting submitted even if the input is not valid. How can I prevent the form from being submitted?

anechkayf
  • 481
  • 1
  • 4
  • 12
  • 1
    And your question is? – Scott Marcus Nov 12 '20 at 18:42
  • @ScottMarcus sorry I was not clear, my form is getting submitted even if the input is not valid. preventDefault is not working – anechkayf Nov 12 '20 at 18:44
  • @KaanCetinkaya sorry I was not clear, my form is getting submitted even if the input is not valid. preventDefault is not working – anechkayf Nov 12 '20 at 18:44
  • 1
    You have two different `submit` handlers set up. The one in JavaScript looks correct, but you also have an inline handler, which should be removed. `onsubmit="return generateTable();"` – Scott Marcus Nov 12 '20 at 18:46
  • @ScottMarcus if I remove the inline handler then the Submit button doesn't do anything when I click it. How should I call the generateTable() function then? – anechkayf Nov 12 '20 at 18:55
  • That’s the point. If you remove the inline handler, only the JavaScript handler remains and that one is currently set to prevent the submit. Call the function from the JavaScript handler. – Scott Marcus Nov 12 '20 at 21:06

1 Answers1

1

You don't need to call the submit function, just use as following.

$("#inputForm").validate({
    rules: {
        "name": {
            required: true,
            minlength: 5
        },
        "email": {
            required: true,
            email: true
        }
    },
    messages: {
        "name": {
            required: "Please, enter a name"
        },
        "email": {
            required: "Please, enter an email",
            email: "Email is invalid"
        }
    },
    submitHandler: function (form) { // for demo
        alert('valid form submitted'); // for demo
        return false; // for demo
    }
});

See this fiddle here

Muhammad
  • 6,725
  • 5
  • 47
  • 54