Following are just my views and results of experiments that i have done.Please let me also know in case you find better practices available.
We have often come across code which is difficult to maintain due to understanding the implementation done by the author.This is not necessarily because of the the technical complexity , but because of the way the things are done.Hence having a standard naming convention would solve half of the problem.On having a self documented code , things can get little more easier.
A common problem faced by most of the developers is that of validating elements in a form.Now , this case would be solved in different ways by different developers.Over a period of time , when a new validation is to be added , a new comer may bring up code as per his own idea.As time passes by the application has different ways of doing the samething.This adds to the pain of understanding the implementation.
The following solution has helped me to make it quite easy , implementing validations for form elements.
1.Have a common function to validate all the fields.This should be invoked when the form
is being submitted.
2.The form itself should be taken as a parameter to the function.This makes it easy to access the form elemetns ( As shown below ).
<form id="frmDemoForm" name="frmDemoForm" onsubmit="return validateFormFields(this);">
<script>
//function to validate the form fields
function validateFormFields(pForm){
var vName = pForm.txtName.value;
if (vName==""){
return raiseErrorAndRetainFocus(pForm.txtName,"Name cannot be left blank")
}
//function to raise errors and retain focus on the fields.
function raiseErrorAndRetainFocus(pField,pErrorMsg){
alert(pErrorMsg);
pField.focus();
return false;
}
}
</script>