DHTML Form Enhancement - Extending the validate function
(Page 5 of 5 )
Some simple ways to extend the form's validation support would be to build in regex-based validation types to check for common data types such as phone numbers, email addresses, and postal codes. You could use validate="email" and add a section in the validate function's case statement to handle that type of validation. You could also extend the function to support confirmation prompts and suggestion boxes when users enter invalid data or to verify that a user understands what the data in the form will be used for and give them a chance to choose not to submit or to make changes to their information. I want to look at one last function before I conclude the article, however. It addresses another very common issue - autosubmitting a form when a selection has been made from a select box.
The need to submit a form automatically when a user makes a selection from a select box is fairly common. It could be used to direct a user to some relevant page on a site, or to allow the user to select the first piece of information from a series of questions building to a more specific form (think kelley blue book's website when you're digging down to the type of car you want to get pricing informatin for). Consider the following DHTML function:
function formsubmit(thisfield) {
var thisform;
if (!thisfield)
return;
thisform = thisfield.form;
if (thisfield.selectedIndex) {
if (thisfield.selectedIndex != 0)
thisform.submit();
else
return;
}
else if (thisfield.value != '')
thisform.submit();
else
return;
}
Usage is as follows:
<select onchange="formsubmit(this);"></select>
The function makes sure that a valid selection was made and submits the form if it has. It is beneficial to set the default selected option to an option with an empty value labelled --SELECT-- or something similar (or whatever suits your application).
Conclusion
While the functions discussed in this article are not especially complex, they are simple to extend and provide short and 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.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |