
/* *****************************************************************
  This Javascript is created for validation of all the form fields
  -validation for string ,numeric,date,email.tel,fileextention  etc.
  
  Author:Mainul Islam
  Date  :28/06/2001
  Last modified: 2/7/2001
  *****************************************************************
*/

  
  var checkObjects	= new Array(); //to store the form fields
  var errors		= "";
  var returnVal		= false;
  var language		= new Array(); //to store the error messages
  language["header"]	= "The following error(s) occured:"
  language["start"]	= "->";
  language["field"]	= " Field ";
  language["require"]	= " is required";
  language["min"]	= " and must consist of at least ";
  language["max"]	= " and must not contain more than ";
  language["minmax"]	= " and no more than ";
  language["chars"]	= " characters";
  language["num"]	= " and must contain a number";
  language["email"]	= " must contain a valid e-mail address";
  language["tel"]       = " not a valid telephone number" ; 
  language["file"]      = " not a picture file";
  language["date"]      = " startdate must be less than enddate";
  language['deletdate'] = " Deletingdate must be less than startDate/enddate";
// -----------------------------------------------------------------------------
// define_For_Validation - Call this function in the beginning of the page. I.e. onLoad.
// fieldName= name of the input field (Required)
// fieldType= string, num, email(Required),tele(Not Required),file,date
// HTMLname= name to identify the field to the user 
// min = the value must have at least [min] characters (Optional)
// max = the value must have maximum [max] characters (Optional)
// d = (Optional, default value is document)
// -----------------------------------------------------------------------------


  function define_for_validation(fieldName, fieldType, HTMLname, min, max, d) 
  {
    // This function names the form, which we don't know
   // Checks for each field in case that multiple forms are presents
     var p;     //needed for frameset
     var i;
     var frmFields; //needed for the form fields

   // if d is not described, setting d as the object Document
    if (!d) 
    {
     d = document; 
    }



 // adding frame name before naming form, if frames are used

   /*if ((p=fieldName.indexOf("?"))>0&&parent.frames.length) 
    {
      d = parent.frames[fieldName.substring(p+1)].document;
      fieldName = fieldName.substring(0,p);
    }*/



 // if browser is IE, take into account that form can be placed in a layer

    if (!(frmFields = d[fieldName]) && d.all) 
    {
     frmFields= d.all[fieldName];

    }


// **************



//this is for counting the form numbers 
//and the fields of the each form sent for validation by init method((multiple forms))

    for (i = 0; !frmFields && i < d.forms.length; i++) 
    {

     frmFields = d.forms[i][fieldName];   // x gives the input tag of the current form
     
    }



// **************



// if browser is NS, take into account that form can be placed in a layer

   /*for (i = 0; !x && d.layers && i < d.layers.length; i++) 
    {
      frmFields = define_For_Validation(fieldName,fieldType, HTMLname, min, max, 
d.layers[i].document);
       return frmFields;       
    }*/

//making the input fields as objects
    eval("V_"+fieldName+" = new formResult(frmFields,fieldType, HTMLname, min, max);"); 
 

//storing the objects in the checkObjectsarray with the name of v_field0 etc    

    checkObjects[eval(checkObjects.length)] = eval("V_"+fieldName);  

  }                                                        

// now we know the true name of the form and fields!! So name it...

  function formResult(form, type, HTMLname, min, max)
  {
   this.form = form;
   this.type = type;
   this.HTMLname = HTMLname;
   this.min= min;
   this.max  = max;
  }


//We can validate the form fields one by one by calling this function named "validate"

  function validate() 

  {
   // the following global variables containes the combination of more than one fields 
    var startDate; 
    var endDate;
     var deletingDate;
//starting for validation those objects stored in  checkObjects array

    if (checkObjects.length > 0)

    { 
      errorObject = "";
      for (i = 0; i < checkObjects.length; i++) 
      {
  
       validateObject = new Object();
       validateObject.form = checkObjects[i].form;
       validateObject.HTMLname = checkObjects[i].HTMLname;

   //if the field is dropdownlist then restrict them to enter here
      
       if(validateObject.HTMLname !="startDate" && validateObject.HTMLname !="endDate" && validateObject.HTMLname !="deletingDate")
       { 
         validateObject.val = checkObjects[i].form.value;
         validateObject.len = checkObjects[i].form.value.length;
       }
        validateObject.min = checkObjects[i].min;
        validateObject.max = checkObjects[i].max;
        validateObject.type = checkObjects[i].type;

   //if the field is dropdownlist then  enter here otherwise not
       if(validateObject.HTMLname =="startDate" || validateObject.HTMLname =="endDate" || validateObject.HTMLname =="deletingDate")
       {
         validateObject.selectedIndex = checkObjects[i].form.selectedIndex;
  
       }
  //this is for checking the the string or nummeric fields are filled or not

       if (validateObject.type == "num" || validateObject.type == "string") 
       {
         if ((validateObject.type == "num" && validateObject.len <= 0) || (validateObject.type == 
"num" && isNaN(validateObject.val)))
          {
             errors += language['start'] + language['field'] + validateObject.HTMLname + 
language['require'] + language['num'] + "\n";
          } 
          else if (validateObject.min && validateObject.max && (validateObject.len < 
validateObject.min || validateObject.len > validateObject.max)) 
          {
             errors += language['start'] + language['field'] + validateObject.HTMLname + 
language['require'] + language['min'] + validateObject.min + language['minmax'] + 
validateObject.max+language['chars'] + "\n";
          } 
          else if (validateObject.min && !validateObject.max && (validateObject.len < 
validateObject.min))
          { 
             errors += language['start'] + language['field'] + validateObject.HTMLname + 
language['require'] + language['min'] + validateObject.min + language['chars'] + "\n";
          }
          else if (validateObject.max && !validateObject.min &&(validateObject.len > 
validateObject.max))
          { 
            errors += language['start'] + language['field'] + validateObject.HTMLname + 
language['require'] + language['max'] + validateObject.max + language['chars'] + "\n";
          } 
          else if (!validateObject.min && !validateObject.max && validateObject.len <= 0)
          { 
          errors += language['start'] + language['field'] + validateObject.HTMLname + 
language['require'] + "\n";
   
           }
        } 




//*************Validation for email starts here*****************

        else if(validateObject.type == "email")
        {
          var invalidEmailChar ="no";
          if(validateObject.len>0)
           { 
              //this variable contains the valid characters characters for an email address 
             validEmailChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@._";
         
             
        //for checking the input characters are matched with valid characters or not
             for (l=0; l<validateObject.len; l++)
         
             {
               presentChar=validateObject.val.charAt(l);
           
               for(m=0;m< validEmailChars.length ; m++)  //for having the valid characters for caompare with input ones
               {
                 if(presentChar== validEmailChars.charAt(m)) //if valid and input get similarity 
//then enters here gor for next check
                 { 
                    invalidEmailChar="no";
                    m= validEmailChars.length;
                 
                 }
                
              
             
                   
            
         
                 else
                 {              
                   invalidEmailChar="yes";
               
                   if(m==validEmailChars.length-1)
                   { 
                    l=validateObject.len;
                   }
              
                 }  
            
       

               }
   
            } 


           if ((validateObject.val.indexOf("@") ==-1) || (validateObject.val.charAt(0) == ".") || 
(validateObject.val.charAt(0) == "@") || (validateObject.len < 6) || 
(validateObject.val.indexOf(".") == -1) || 
(validateObject.val.charAt(validateObject.val.indexOf("@")+1) == ".") || 
(validateObject.val.charAt(validateObject.val.indexOf("@")-1) == 
".")||(validateObject.val.charAt(validateObject.len-1) == ".")) 
           { 
            invalidEmailChar="yes";
           }  
     
       
     
           if(invalidEmailChar=="yes")   
           {  
            errors += language['start'] + language['field'] + validateObject.HTMLname + 
language['email'] + "\n"; 
           }
     
         
        }   
 
    }


//*************Validation for email ends here*****************


	

//************** Validation for telephone starts here**********************
   
    else if(validateObject.type == "tele") 

    { 
      validTeleChars="()+- 1234567890";  //valid characters for telephone
  
      var invalidTeleChar="no"; //this variable indicates the errore message when its value is 
//"yes"
      var number=0;         //for counting how many numeric value are in input telephone
    
      if(validateObject.len>0)
      {
        //for checking the input characters are matched with valid characters or not
        for (j=0; j<validateObject.len; j++)
         
        {
            presentChar=validateObject.val.charAt(j);
           
            for(k=0;k<validTeleChars.length;k++)          //for having the valid characters for 
//caompare with input ones
            {
              if(presentChar==validTeleChars.charAt(k))    //if valid and input get similarity 
//then enters here gor for next check
              { 
                invalidTeleChar="no";
                k=validTeleChars.length;
                 
              }
                
             
             
                   
            
         
               else
               {              
                 invalidTeleChar="yes";
               
                 if(k==validTeleChars.length-1)
                 { 
                  j=validateObject.len;
                 }
              
               }  
            
       

            }
              //searching for numeric values
             if(!(isNaN(parseInt(presentChar))))
            
             {
               number+=1;
             } 
         
               
             if(j==validateObject.len-1 && number<3)
             {
              invalidTeleChar="yes";

             }
             // if first character is"(" then check if there is ")" and their content or not 
             if(validateObject.val.charAt(0)=="(")
             { 
              if(((x=validateObject.val.indexOf(")"))-(y=validateObject.val.indexOf("(")))<2)
               {
                 invalidTeleChar="yes";
               }
             }
               // this scope for validating the presence of  numeric value in ()
              /* for(p=x+1; p<y;p++)
               {

                 if(!(isNaN(validateObject.val.charAt(p))))
                  {
                    countNumber+=1;
                    if(countNumber<2)  {invalidTeleChar="yes";} 
                  }

                }
             }
  
             
            }*/
         
       } 
       

        
       if(invalidTeleChar=="yes")   
       {  
         errors += language['start'] + language['field'] + validateObject.HTMLname + 
language['tel']  +"\n"; 
       }
     
         
    
       else 
       {
         validateObject.val=0;  // if input is not filled then telephone is 0;
       } 
     } 
    
   }

//************** Validation for telephone ends 


  


//**********Validation for image file extention starts here ***************
     
             
            else if(validateObject.type == "imgextn") 
              {
                 
                if (validateObject.val!="")
                
                {
                   
                   
                   var picPath=validateObject.val;
                                       
                   var picPathLen=picPath.length;
                   var lastDot=picPath.lastIndexOf(".");                 
                   var charAfterLastDot =lastDot+1;	   	
	           var newExtn= picPath.substring(charAfterLastDot,picPathLen).toLowerCase();	
                   

                   

                   if (newExtn=="gif" || newExtn=="jpg" ||newExtn=="png"||newExtn=="jpeg")
	             
                   {		        

                      errors +="";
	                   
                    }
	
	            else
                    {
                        errors += language['start'] + language['field'] + validateObject.HTMLname 
+ language['file'] + ". It is " + newExtn +" file" +"\n"; 
   		      
                     } 
             

                   }

                }
                 
//***************Validation for Imagefile ends here********************** 





 

//****************Validation for Date difference starts here*************** 

  if(validateObject.HTMLname =="startDate" ||validateObject.HTMLname=="endDate"||validateObject.HTMLname=="deletingDate")
              {
                 var startMonthIndex; var endMonthIndex; 
                 var startDayIndex;   var endDayIndex;
                 var startYear;       var endYear;

                             var deletingMonthIndex;  
                             var deletingDayIndex;   
                              var deletingYear; 
                 //collecting the month,day and year according to input
                 if(validateObject.type =="startMonth")
                 {
                   startMonthIndex=validateObject.selectedIndex;
                 }
                 if(validateObject.type =="startDay")
                 {
                   startDayIndex=validateObject.selectedIndex;
                 }
                 if(validateObject.type =="startYear")
                 {
                   startYear=validateObject.form.options[validateObject.selectedIndex].value;
                 }
   
                 if(validateObject.type =="endMonth")
                 {
                   endMonthIndex=validateObject.selectedIndex;
                 }
                 if(validateObject.type =="endDay")
                 {
                   endDayIndex=validateObject.selectedIndex;
                 }
                 if(validateObject.type =="endYear")
                 {
                   endYear=validateObject.form.options[validateObject.selectedIndex].value;
                 }
                 if(validateObject.type =="deletingMonth")
                 {
                   deletingMonthIndex=validateObject.selectedIndex;
                 }
                 if(validateObject.type =="deletingDay")
                 {
                   deletingDayIndex=validateObject.selectedIndex;
                 }
                 if(validateObject.type =="deletingYear")
                 {
                   deletingYear=validateObject.form.options[validateObject.selectedIndex].value;
                 }


                 //Now setting the total Date formate for startdate
                 startDate=new Date(endMonthIndex);
                 startDate.setMonth(startMonthIndex);
                 startDate.setDate(startDayIndex+1);
                 startDate.setFullYear(startYear);

                  //Now setting the total Date formate for enddate  
                 endDate=new Date();
                 endDate.setMonth(endMonthIndex);
                 endDate.setDate(endDayIndex+1);
                 endDate.setFullYear(endYear); 

                    //Now setting the total Date formate for deletingdate  
                 deletingDate=new Date();
                 deletingDate.setMonth(deletingMonthIndex);
                 deletingDate.setDate(deletingDayIndex+1);
                 deletingDate.setFullYear(deletingYear); 

            }

         }
    
      }

           
    

  if(startDate>endDate)

    {
       errors += language['start'] + language['field'] + "Date " + language['date']  +"\n"; 
      
    }  
    
  if(deletingDate<endDate ||deletingDate<startDate )

    {
       errors += language['start'] + language['field'] + "Date " + language['deletdate']  +"\n"; 
      
    } 
    
    

//****************Validation for Date difference ends here*************** 
  /*else if(validateObject.type == "check") 
  
  { alert(validateObject.val);
  	
  	}*/

  
//***************** validation results are here*************************
   if (errors)
   {
    alert(language["header"].concat("\n"+errors));
    errors = "";
    returnVal = false;
   } 
   else
   {
    returnVal = true;
   
   }

 }

 //*************function ends here****************
