darkhorse
darkhorse

Reputation: 8732

How do I stop form validation by overriding the onsubmit event?

I am trying to stop the browser from validating the form on submit. I have overridden the onsubmit event to use my own function. Unfortunately, when I submit the form, it is still validated, and my function does not run. The following is the code:

function submitFunction() {
  alert("Name is required.");
  event.preventDefault();
}
<form  onsubmit="submitFunction()">
  <input type="text" placeholder="Name" required>
  <input type="submit" value="submit">
</form>

How can I fix this? Thanks for any help!

Upvotes: 1

Views: 658

Answers (1)

norbitrial
norbitrial

Reputation: 15166

If you add to your form the attribute called novalidate then it will call your function:

function submitFunction() {
  alert("Name is required.");
}
<form onsubmit="submitFunction()" novalidate>
  <input type="text" placeholder="Name" required>
  <input type="submit" value="submit">
</form>

From the documentation of <form>:

This Boolean attribute indicates that the form shouldn't be validated when submitted. If this attribute is not set (and therefore the form is validated), it can be overridden by a formnovalidate attribute on a <button>, <input type="submit">, or <input type="image"> element belonging to the form.

Upvotes: 5

Related Questions