|
||
| Inside Technique : Form Validation Made Easy : Roll Your Own Methods You may have realized in the example of our anonymous function that an entire function object is stored as a local variable: var fCube = function (x){ return x*x*x; }
You also know that any property of an element can be declared as an expando property. If we combine the use of both techniques, we can assign a function to a property of an element. You may recognize this as a method created on the myDate textbox: document.oForm.myDate.valid = function (){
// code to check date (returns false if validation fails)
var eEvent=this.getAttribute("onvalidate");
if(eEvent){
if(typeof eEvent!="function")
eEvent=new Function(eEvent);
if(eEvent()==false)
return false;
}
return true;
}
Since valid is a property of myDate, we use the "this" keyword to refer to the myDate object. It's just that easy to put methods on your elements. In order to perform validation on a form element, I can create a "valid" method (as above) on each field which returns a boolean value telling me whether or not it has passed the validation check. For example, to test whether a required textbox field is filled in, I test to see if the "required" attribute is set on the element and if the value for the field is something other than whitespace. oElement.valid = function () {
if (this.getAttribute("required")!=null && !el.value.replace(/\s/g,""))
return false;
}
In order to make this method somewhat useful, we will need to expand on its functionality. Notice the /\s/g in the test. This object is called a regular expression. This particular regular expression matches all occurrences of whitespace in the string. Let's take a quick look at regular expressions. Page 1:Form Validation Made Easy © 1997-2000 InsideDHTML.com, LLC. All rights reserved. |