Bring Your Forms to Life With Javascript / Page 3 Live forms | WebReference

Bring Your Forms to Life With Javascript / Page 3 Live forms


[prev]

Bring Your Forms to Life With Javascript [con't]

Tying the Object to the Form

The best part about creating an object like this is that tying it to the form that we created in listing 1 is straightforward, as is the method to tie it to any form in the future. The first thing to do is to import the JavaScript object along with the helper utils file (included in the source download), add ids to all elements so we can target them appropriately, then add an event to the field. In this case I choose onblur to make sure that the field had been completed by the user before validating. Within this event, simply add Validator.Validate(this) or Validator.Validate(this, "email") in order to validate an email or other custom element. In the body onload event, add the Initialize method and enter the appropriate ids, image paths and number of required fields as the parameters. Lastly, we add an onsubmit event to the form and make sure that all fields have been validated before allowing it to post. Listing 3 shows the new form incorporated with the Validator.