4

I want to know if submit gets called if my form data are not valid in html5 validation. For example I have a form id personal_info.

I use the following block to get on submit event :

$("#personal_info").submit(function(event) { event.preventDefault(); saveData("personal_info"); }); function saveData(formName){ console.log("test"); } 

Is is the default behavior that the function saveData gets called on submit because even if my form is not valid the function gets called.

How to prevent submit function from being called if my form is invalid?

4
  • 1
    Try on top of submit handler: if(!$(this).valid()) return; Commented Dec 27, 2014 at 14:14
  • There seems to be a hard-coded call to saveData, I'd say it's very default JS behavior to execute that function. Commented Dec 27, 2014 at 14:15
  • It works but should on submit be called if the form is not valid. However thanks solved my problem Commented Dec 27, 2014 at 14:18
  • Please do not use the jquery-validate tag when the question has nothing to do with this plugin. Commented Dec 28, 2014 at 16:59

2 Answers 2

4

The new HTML5 validation APIs will not submit an invalid form unless you use the novalidation attribute on the form. See https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation for more information.

Sign up to request clarification or add additional context in comments.

Comments

2
It works but should on submit be called if the form is not valid. 

Anytime your form #personal_info is submitted, the submit function will run.

The reason it may appear that the submit function isn't running, is because of this line

event.preventDefault(); 

This prevents the default action from taking place, which is submitting the form. So the form won't submit normally, thus your web page won't reload/refresh.

Calling submit even if the form is not valid, is just fine. Nothing wrong with that. The way your code is in your question, the saveData function is set to run each time, even if it's not valid. So we can change that from happening.

Like A. Wolff said in the comments, you could just wrap an if statement around your call to saveData function.

So you could have your code look something like this

$("#personal_info").submit(function(event) { event.preventDefault(); if ($(this).valid()) { // if form is valid saveData("personal_info"); // then do this } }); function saveData(formName){ console.log("test"); } 

1 Comment

The new HTML5 validation APIs will not submit an invalid form unless you use the novalidation attribute on the form. See developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.