2005-11-10

Web - Js: generic form validation function

function isSomethingSelected( obj ){
    for (var r=0; r < obj.length; r++){
     if ( obj[r].checked ) return true;
  }
}

/*--- form validation--- */
function checkRequiredField(sFname)
  {
   field = self.document.getElementById(sFname);
   sType = field.type.toLowerCase();
   var bOk = true;

   switch (sType)
   {
    case "text":
    case "textarea" :
     if (field.value=="") bOk=false;
     break;
    case "checkbox":
    case "radio":
     if ( !field[0]) { //handle single item group first
      if ( !field.checked ) bOk=false;
     }
     else
     {
      if (!isSomethingSelected(field)) bOk=false;
     }
     break;
    case "select-one":
     if (field.selectedIndex == 0) bOk= false;
     break;
    case "select-multiple":
     if (field.selectedIndex == -1) bOk=false;
     break;
    default:
     break;
   }
  return bOk;
}

No comments:

Post a Comment