|
||
| Inside Technique : Form Validation Made Easy : Capturing Event Handlers One way to prevent conflicting results within the same page is to allow for and expect conflicts. Conflicts arise when different developers need to handle the same event with different code. For example, Bob writes his own custom script to perform specific tasks in the onsubmit event handler of a form, yet I need to validate the form fields to ensure the data passed to the server is usable. In order to keep my code generalized, I need to account for pre-defined event handlers which Bob may have written for any pages. You can capture the existing event handler and run it from within your own code. The key factor is grabbing for the handler after it is already defined. The following sample code could be placed within a .js file included in a page to add validation. function fValidate(){
// my validation code
}
var oForm=document.myForm;
if(oForm.onsubmit){
var fSubmit=oForm.onsubmit;
oForm.onsubmit=new Function("fValidate(); fSubmit();");
}else{
oForm.onsubmit=fValidate;
}
I check to see if any code already exists in the onsubmit property of the form object. If there is code, I absorb it into my new function; otherwise, I can assign the event handler with a function pointer as normal. Another situation you may need to handle includes the use of return values to cancel event processing (e.g., returning false inside an onsubmit handler). To deal with a return value, you simply need to check for its value. For example, if the existing onsubmit handler [fSubmit] returned false to cancel the event, you want to keep the same functionality by returning false. You also need to cancel the submit if the validation function finds an error. oForm.onsubmit=new Function("if(fValidate()==false)return false; return fSubmit();");
For more complex functions, the Function constructor becomes tedious. It requires that you write the entire body of the new function as a string, complete with escape sequences. Defining everything through function pointers can get equally bad for large development efforts because of the increased chance for namespace collisions. Anonymous functions offer a reprieve from the madness. Page 1:Form Validation Made Easy © 1997-2000 InsideDHTML.com, LLC. All rights reserved. |