There are few tools to speed up form development. This article illustrates simple ways to provide some basic enhancements to your web application's forms such as validation, automatic submission, and hilighting of the field in focus.
DHTML Form Enhancement - Extensible Validation (Page 3 of 5 )
Consider the following DHTML:
function isNotEmpty(elem) { var str = elem.value; if(str == null || str.length == 0) return false; else return true; }
// THIS FUNCTION PERFORMS VALIDATION BASED ON A SET OF CUSTOM HTML ATTRIBUTES function validate(form) { var attrVal, attrReg, attrEq, attrFail, strTemp;
for (var i = 0; i < form.length; i++) { attrVal = form[i].getAttribute("validate");
switch (attrVal) { case 'required' : if (!isNotEmpty(form[i])) { attrFail = form[i].getAttribute("failure");
if (attrFail) alert(attrFail); else alert('You must complete all required form fields.'); form[i].focus(); return false; } break;
case 'regex' : attrReg = form[i].getAttribute("regex"); if (attrReg != null && attrReg.length != 0) { var regex = new RegExp(attrReg); strTemp = form[i].value; if (!strTemp.match(regex)) { attrFail = form[i].getAttribute("failure");
if (attrFail) alert(attrFail); else alert('Invalid data format at field "' + form[i].name + '".'); form[i].focus(); return false; } } break;
case 'equals' : attrEq = form[i].getAttribute("equals"); var objEq = document.getElementById(attrEq); if (objEq) { if (form[i].value != objEq.value) { attrFail = form[i].getAttribute("failure");
if (attrFail) alert(attrFail); else alert('Form fields do not match');
form[i].focus(); return false; } } break; }
}
return true; }
Examine the function above; the most notable part of the function is the switch statement that tests the value of the element's 'validate" attribute. The function supports required field validation, field equality validation, and regular expression validation. The isNotEmpty function is just a wrapper function to make sure a field is not empty. To enable the form to use validation, we will use the following code for the form's onsubmit handler:
<form onsubmit="return validate(this);" ></form>
The code in the validate function provides functionality to validate information in form fields. Using this DHTML, to make a form field required, we would use the following markup:
<input validate="required" />
Obviously you would have more attributes but this example shows how to use the DHTML above to make a form field required. The next page will discuss slightly more complex uses of the function.