Nicsoft Nicsoft - 1 year ago 33
HTML Question

JQuery .validate triggered first on the second submit

I am trying to validate a form. The form is dynamically generated and added to div on the page. When submitting the form I want the validation to be performed at once. What happens now is that the first time I submit the form is posted without being validated. The second time I hit submit it's validate.

Here is my script:

$("#registerform").live("submit", function(e){
//Prevent the form from submitting normally
rules: {
firstname: "required",// simple rule, converted to {required:true}
surname: "required",
//phonenumber: "required",
address: "required",
// address2: "required",
zipcode: "required",
username_ID: "required",
city: "required",
companyname: "required",
email: {// compound rule
required: true,
email: true
messages: {
firstname: "Förnamn saknas" ,
surname: "Efternamn saknas",
address: "Adress saknas",
// address2: "required",
zipcode: "Postkod saknas",
username_ID: "Användarnamn saknas",
city: "Ort saknas",
companyname: "Företagsnamn saknas",
email: "Korrekt emailadress saknas"
//alert the response from the server

My form:

<form id='registerform' action='registeraccount.php' method='post'>
Ägare av konto</br>
* Förnamn: <input type='text' name='firstname' /> <br/>
* Efternamn: <input type='text' name='surname' /> <br/>
* Email: <input type='text' name='email' /> <br/>
* Telefon: <input type='text' name='phonenumber' /> <br/>
Företagsinformation: </br>
* Adress: <input type='text' name='address' /> <br/>
Adress: <input type='text' name='address2' /> <br/>
* Postnummer: <input type='text' name='zipcode' /> <br/>
* Ort: <input type='text' name='city' /> <br/>

<div id='username_message'></div>
* Användarnamn: <input id='username_ID' type='text' name='username' />

* Företagsnamn (som kunden kommer se det): <input type='text' name='companyname' /> <br/>
Organisationsnummer: <input type='text' name='organisationnumber' /><br/>
<input id='submitaccountregistration' type='submit' value='Submit Comment' />

How come it's not triggered on the first submit and how can I get the validation to be performed the first time I hit submit?

Answer Source

At first submit event you are not validating form, but just attaching validator plugin to it. At second submit you are validating it and attaching validation again.

Just define function which adds your validation (function attachValidate(form) { $(form).validate... }) and run this function when form is generated/loaded.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download