I am trying to validate a form with the jquery-validate plugin. The html page doesn’t show the error messages from the validation until I click submit twice. I know the submit event is being received on every click (including the first one) because I placed an alert in the javascript to verify.
I can also see the form is submitted because I see the parameters show up in the address bar after the first click. Do I have to do something to force the error messages to show up the first time?
Here how I’m adding the validation:
<script type="text/javascript">
$("form").submit(function() {
$("form").validate({
rules: {
match: "required",
limit: "required"
},
messages: {
match: "Please enter a match"
},
});
});
</script>
Here is a snippet of my form:
<form action="#">
<fieldset>
<legend>Smart Playlist</legend>
<div class="control-group">
<label class="control-label">
<input type="checkbox" name="match" value="match" class="chkbox"/>
</label>
</div>
</fieldset>
</form>
You do not need to enclose it within the
.submit()handler because the Validation Plugin takes care of that already. Please refer to the official demo page for working examples.BTW- you also had a trailing comma after the
messages:options. Certain versions of IE would choke on that. This is the “Trailing Comma of Death” and it only affects certain versions of IE… other browsers’ tools may not flag it as an error because it’s technically not an error.A more detailed explanation of what was happening:
Since you enclosed
.validate()within.submit(), the Validation function does not even load until you hit submit. Since it’s not already loaded when you hit submit, no validation will occur. Then when you hit submit the second time, the function is now loaded so it appears to work normally.When you enclose
.validate()withindocument.ready, the Validation plugin loads immediately as the DOM is finished loaded. Therefore, it’s ready and waiting for you to interact with your form and it behaves correctly on the first submit.