The
on()
function loads the validate on the form when I press submit. ... So what happens now is the form is not submitted but the errors only show when I press submit a second time.
You are correct. The plugin is not initialized on your form until you click submit
the first time. This is because, with on()
, you are simply attaching the plugin's initialization function to a submit
event. No matter how you do this, delegate
, bind
, etc., your problem will be the same... you'll never properly initialize the plugin until after that first click.
So what happens now is the form is not submitted
Your preventDefault()
is blocking the normal submit. You need to get rid of all this and simply call .validate()
immediately after you construct the form's HTML.
Is there any way to fix this?
You must initialize the plugin (one time) immediately after you load the form with your ajax
. Where is the code that does this? Try putting your .validate()
function inside of the complete
callback function of the ajax
that loads your form. This will run .validate()
once upon completion of the ajax
.
Or if you use jQuery .load()
...
$('#content').load('form_loader', function() {
('#myform').validate(); // initialize plugin after form is loaded
});
Without seeing your ajax
code, the crude demo below was quickly constructed to only simulate this concept. Click the "test" button to load a form with ajax
, which then initializes .validate()
upon completion.
You can see the form is loaded into a div
and ready to validate before the very first click.