Solved

Validation Script change... makes input boxes/select list/radio/checkbox red if entered incorrectly

Posted on 2004-08-22
16
474 Views
Last Modified: 2012-06-27
Beware.. this is a difficult one!  When a user enters multiple fields wrong.. the error message will list all fields that are either missing or entered incorrectly.  And after that it makes all the incorrect inputbox/selectbox/radio/checkbox red(or users choice of color) it will also change the font color to user's choice of color as well...

curently it only goes through only 1 error at a time...

Here's the current script and example usage:

function Validator(frmname)
{
    this.formobj=document.forms[frmname];
      if(!this.formobj)
      {
        alert("BUG: couldnot get Form object "+frmname);
            return;
      }
      if(this.formobj.onsubmit)
      {
       this.formobj.old_onsubmit = this.formobj.onsubmit;
       this.formobj.onsubmit=null;
      }
      else
      {
       this.formobj.old_onsubmit = null;
      }
      this.formobj.onsubmit=form_submit_handler;
      this.addValidation = add_validation;
      this.setAddnlValidationFunction=set_addnl_vfunction;
      this.clearAllValidations = clear_all_validations;
}
function set_addnl_vfunction(functionname)
{
  this.formobj.addnlvalidation = functionname;
}
function clear_all_validations()
{
      for(var itr=0;itr < this.formobj.elements.length;itr++)
      {
            this.formobj.elements[itr].validationset = null;
      }
}
function form_submit_handler()
{
      for(var itr=0;itr < this.elements.length;itr++)
      {
            if(this.elements[itr].validationset &&
         !this.elements[itr].validationset.validate())
            {
              return false;
            }
      }
      if(this.addnlvalidation)
      {
        str =" var ret = "+this.addnlvalidation+"()";
        eval(str);
    if(!ret) return ret;
      }
      return true;
}
function add_validation(itemname,descriptor,errstr)
{
      if(!this.formobj)
      {
            alert("BUG: the form object is not set properly");
            return;
      }//if
      var itemobj = this.formobj[itemname];

    if(itemobj.length && isNaN(itemobj.selectedIndex) )
    //for radio button; don't do for 'select' item
      {
            itemobj = itemobj[0];
      }      
      if(!itemobj)
      {
            alert("BUG: Couldnot get the input object named: "+itemname);
            return;
      }
      
      if(!itemobj.validationset)
      {
            itemobj.validationset = new ValidationSet(itemobj);
      }
      itemobj.validationset.add(descriptor,errstr);
}
function ValidationDesc(inputitem,desc,error)
{
    this.desc=desc;
      this.error=error;
      this.itemobj = inputitem;
      this.validate=vdesc_validate;
}
function vdesc_validate()
{
 if(!validateInput(this.desc,this.itemobj,this.error))
 {
    this.itemobj.focus();
            return false;
 }
 return true;
}
function ValidationSet(inputitem)
{
    this.vSet=new Array();
      this.add= add_validationdesc;
      this.validate= vset_validate;
      this.itemobj = inputitem;
}
function add_validationdesc(desc,error)
{
  this.vSet[this.vSet.length]=
  new ValidationDesc(this.itemobj,desc,error);
}
function vset_validate()
{
   for(var itr=0;itr<this.vSet.length;itr++)
       {
         if(!this.vSet[itr].validate())
             {
               return false;
             }
       }
       return true;
}
/*  checks the validity of an email address entered
*   returns true or false
*/
function validateEmail(email)
{
    var splitted = email.match("^(.+)@(.+)$");
    if(splitted == null) return false;
    if(splitted[1] != null )
    {
      var regexp_user=/^\"?[\w-_\.]*\"?$/;
      if(splitted[1].match(regexp_user) == null) return false;
    }
    if(splitted[2] != null)
    {
      var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
      if(splitted[2].match(regexp_domain) == null)
      {
          var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
          if(splitted[2].match(regexp_ip) == null) return false;
      }// if
      return true;
    }
return false;
}

function TestComparison(objValue,strCompareElement,strvalidator,strError)
{
   var bRet=true;
   var objCompare=null;
   if(!objValue.form)
   {
      alert("BUG: No Form object!");
        return false
   }
   objCompare = objValue.form.elements[strCompareElement];
   if(!objCompare)
   {
     alert("BUG: Element with name"+strCompareElement+" not found !");
     return false;
   }
   if(strvalidator != "eqelmnt" &&
           strvalidator != "neelmnt")
   {
      if(isNaN(objValue.value))
      {
        alert(objValue.name+": Should be a number ");
        return false;
      }//if
      if(isNaN(objCompare.value))
      {
        alert(objCompare.name+": Should be a number ");
        return false;
      }//if         
   }//if
   var cmpstr="";
   switch(strvalidator)
   {
       case "eqelmnt":
                  {
                     if(objValue.value != objCompare.value)
                     {
                          cmpstr = " should be equal to ";
                        bRet = false;
                     }//if
                     break;
                  }//case
            case "ltelmnt":
                  {
                  if(eval(objValue.value) >= eval(objCompare.value))
                        {
                         cmpstr =  " should be less than ";
                         bRet = false;                              
                        }
                    break;
                  }//case
            case "leelmnt":
                  {
                        if(eval(objValue.value) >  eval(objCompare.value))
                        {
                         cmpstr =  " should be less than or equal to";
                         bRet = false;                              
                        }
                    break;
                  }//case            
            case "gtelmnt":
                  {
                        if(eval(objValue.value) <=  eval(objCompare.value))
                        {
                         cmpstr =  " should be greater than";
                         bRet = false;                              
                        }
                    break;
                  }//case
            case "geelmnt":
                  {
                        if(eval(objValue.value) < eval(objCompare.value))
                        {
                         cmpstr =  " should be greater than or equal to";
                         bRet = false;                              
                        }
                    break;
                  }//case
            case "neelmnt":
                  {
                     if(objValue.value.length > 0 &&
                       objCompare.value.length > 0 &&
                       objValue.value == objCompare.value)
                     {
                          cmpstr = " should be different from ";
                        bRet = false;
                     }//if
                     break;                  
                  }                  
   }//switch
   if(bRet==false)
   {
      if(!strError || strError.length==0)
        {
          strError = objValue.name + cmpstr + objCompare.value;
        }//if
        alert(strError);
   }//if
   return bRet;
}
function TestSelMin(objValue,strMinSel,strError)
{
    var bret = true;
      var objcheck = objValue.form.elements[objValue.name];
      var chkcount =0;
      if(objcheck.length)
      {
            for(var c=0;c < objcheck.length;c++)
            {
               if(objcheck[c].checked == "1")
               {
                 chkcount++;
               }//if
            }//for
      }
      else
      {
        chkcount = (objcheck.checked == "1")?1:0;
      }
      var minsel = eval(strMinSel);
      if(chkcount < minsel)
      {
            if(!strError || strError.length ==0)
            {
                  strError = "Please Select atleast"+minsel+" check boxes

for"+objValue.name;  
            }//if                                                              
            alert(strError);
            bret = false;
      }
      return bret;
}

function TestDontSelectChk(objValue,chkValue,strError)
{
    var pass=true;
      var objcheck = objValue.form.elements[objValue.name];
    if(objcheck.length)
      {
            var idxchk=-1;
            for(var c=0;c < objcheck.length;c++)
            {
               if(objcheck[c].value == chkValue)
               {
                 idxchk=c;
                   break;
               }//if
            }//for
            if(idxchk>= 0)
            {
              if(objcheck[idxchk].checked=="1")
              {
                pass=false;
              }
            }//if
      }
      else
      {
            if(objValue.checked == "1")
            {
                  pass=false;
            }//if
      }//else
      if(pass==false)
      {
     if(!strError || strError.length ==0)
        {
              strError = "Can't Proceed as you selected "+objValue.name;  
        }//if                   
        alert(strError);
        
      }
    return pass;
}

function TestRequiredInput(objValue,strError)
{
 var ret = true;
    if(eval(objValue.value.length) == 0)
    {
       if(!strError || strError.length ==0)
       {
         strError = objValue.name + " : Required Field";
       }//if
       alert(strError);
       ret=false;
    }//if
return ret;
}

function TestMaxLen(objValue,strMaxLen,strError)
{
 var ret = true;
    if(eval(objValue.value.length) > eval(strMaxLen))
    {
      if(!strError || strError.length ==0)
      {
        strError = objValue.name + " : "+ strMaxLen +" characters maximum ";
      }//if
      alert(strError + "\n[Current length = " + objValue.value.length + " ]");
      ret = false;
    }//if
return ret;
}

function TestMinLen(objValue,strMinLen,strError)
{
 var ret = true;
    if(eval(objValue.value.length) <  eval(strMinLen))
    {
      if(!strError || strError.length ==0)
      {
        strError = objValue.name + " : " + strMinLen + " characters minimum  ";
      }//if              
      alert(strError + "\n[Current length = " + objValue.value.length + " ]");
      ret = false;  
    }//if
return ret;
}

function TestInputType(objValue,strRegExp,strError,strDefaultError)
{
   var ret = true;

    var charpos = objValue.value.search(strRegExp);
    if(objValue.value.length > 0 &&  charpos >= 0)
    {
     if(!strError || strError.length ==0)
      {
        strError = strDefaultError;
      }//if
      alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
      ret = false;
    }//if
 return ret;
}

function TestEmail(objValue,strError)
{
var ret = true;
     if(objValue.value.length > 0 && !validateEmail(objValue.value)       )
     {
       if(!strError || strError.length ==0)
       {
          strError = objValue.name+": Enter a valid Email address ";
       }//if                                              
       alert(strError);
       ret = false;
     }//if
return ret;
}

function TestLessThan(objValue,strLessThan,strError)
{
var ret = true;
        if(isNaN(objValue.value))
        {
          alert(objValue.name+": Should be a number ");
          ret = false;
        }//if
        else
        if(eval(objValue.value) >=  eval(strLessThan))
        {
          if(!strError || strError.length ==0)
          {
            strError = objValue.name + " : value should be less than "+ strLessThan;
          }//if              
          alert(strError);
          ret = false;                
         }//if  
return ret;          
}

function TestGreaterThan(objValue,strGreaterThan,strError)
{
var ret = true;
     if(isNaN(objValue.value))
     {
       alert(objValue.name+": Should be a number ");
       ret = false;
     }//if
       else
     if(eval(objValue.value) <=  eval(strGreaterThan))
      {
        if(!strError || strError.length ==0)
        {
          strError = objValue.name + " : value should be greater than "+ strGreaterThan;
        }//if              
        alert(strError);  
        ret = false;
      }//if  
return ret;          
}

function TestRegExp(objValue,strRegExp,strError)
{
var ret = true;
    if( objValue.value.length > 0 && 
        !objValue.value.match(strRegExp) )
    {
      if(!strError || strError.length ==0)
      {
        strError = objValue.name+": Invalid characters found ";
      }//if                                                              
      alert(strError);
      ret = false;                  
    }//if
return ret;
}
function TestDontSelect(objValue,index,strError)
{
var ret = true;
     if(objValue.selectedIndex == null)
     {
       alert("BUG: dontselect command for non-select Item");
       ret = false;
     }
       else
     if(objValue.selectedIndex == eval(index))
     {
      if(!strError || strError.length ==0)
       {
       strError = objValue.name+": Please Select one option ";
       }//if                                                              
       alert(strError);
       ret =  false;                                  
      }
return ret;
}

function TestSelectOneRadio(objValue,strError)
{
      var objradio = objValue.form.elements[objValue.name];
      var one_selected=false;
      for(var r=0;r < objradio.length;r++)
      {
        if(objradio[r].checked == "1")
        {
              one_selected=true;
            break;
        }
      }
      if(false == one_selected)
      {
      if(!strError || strError.length ==0)
       {
          strError = "Please select one option from "+objValue.name;
         }      
        alert(strError);
      }
return one_selected;
}

//*  Checks each field in a form
function validateInput(strValidateStr,objValue,strError)
{
    var ret = true;
    var epos = strValidateStr.search("=");
    var  command  = "";
    var  cmdvalue = "";
    if(epos >= 0)
    {
     command  = strValidateStr.substring(0,epos);
     cmdvalue = strValidateStr.substr(epos+1);
    }
    else
    {
     command = strValidateStr;
    }

    switch(command)
    {
        case "req":
        case "required":
         {
               ret = TestRequiredInput(objValue,strError)
           break;            
         }
        case "maxlength":
        case "maxlen":
          {
                   ret = TestMaxLen(objValue,cmdvalue,strError)
             break;
          }
        case "minlength":
        case "minlen":
           {
                   ret = TestMinLen(objValue,cmdvalue,strError)
             break;
           }
        case "alnum":
        case "alphanumeric":
           {
                        ret = TestInputType(objValue,"[^A-Za-z0-9]",strError,
                                    objValue.name+": Only alpha-numeric

characters allowed ");
                        break;
           }
        case "alnum_s":
        case "alphanumeric_space":
           {
                        ret = TestInputType(objValue,"[^A-Za-z0-9\\s]",strError,
                                    objValue.name+": Only alpha-numeric

characters and space allowed ");
                        break;
           }              
        case "num":
        case "numeric":
           {
                ret = TestInputType(objValue,"[^0-9]",strError,
                                    objValue.name+": Only digits allowed ");
                break;              
           }
        case "alphabetic":
        case "alpha":
           {
                ret = TestInputType(objValue,"[^A-Za-z]",strError,
                                    objValue.name+": Only alphabetic

characters allowed ");
                break;
           }
        case "alphabetic_space":
        case "alpha_s":
           {
                ret = TestInputType(objValue,"[^A-Za-z\\s]",strError,
                                    objValue.name+": Only alphabetic

characters and space allowed ");
                break;
           }
        case "email":
          {
                     ret = TestEmail(objValue,strError);
               break;
          }
        case "lt":
        case "lessthan":
         {
                ret = TestLessThan(objValue,cmdvalue,strError);
              break;
         }
        case "gt":
        case "greaterthan":
         {
                  ret = TestGreaterThan(objValue,cmdvalue,strError);
            break;
         }
        case "regexp":
         {
                  ret = TestRegExp(objValue,cmdvalue,strError);
           break;
         }
        case "dontselect":
         {
                   ret = TestDontSelect(objValue,cmdvalue,strError)
             break;
         }
            case "dontselectchk":
            {
                  ret = TestDontSelectChk(objValue,cmdvalue,strError)
                  break;
            }
            case "selmin":
            {
                  ret = TestSelMin(objValue,cmdvalue,strError);
                  break;
            }
            case "selone":
            {
                  ret = TestSelectOneRadio(objValue,strError);
                break;
            }            
            //Comparisons
            case "eqelmnt":
            case "ltelmnt":
            case "leelmnt":
            case "gtelmnt":
            case "geelmnt":
            case "neelmnt":
            {
                return TestComparison(objValue,cmdvalue,command,strError);
                break;
            }
    }//switch
    return ret;
}


and here's how it's currently implemented:
after the form:

<form ....>
</form>

<SCRIPT language=JavaScript type="text/javascript">
  var frmvalidator  = new Validator("myform");
<!-- for select list form, uses "dontselect=0" -->
  frmvalidator.addValidation("name1","dontselect=0","Select list error message");
<!-- "req" is for required entry for inputbox -->
  frmvalidator.addValidation("name2","req","inputbox error message");
<!-- "minlen=#" is minimum length requirement -->
  frmvalidator.addValidation("name3","minlen=3", "inputbox minimum length error message");
<!-- "selone" is for radio box requirement selection -->
  frmvalidator.addValidation("name4","selone","Radio box error message");
<!-- "selmin" is for checkbox requirement -->
  frmvalidator.addValidation("name5","selmin=1","checkbox error message");


this is a tough one.. i don't know if anyone has a solution but hey.. worth a try...
0
Comment
Question by:andreni78
  • 9
  • 7
16 Comments
 

Author Comment

by:andreni78
ID: 11865616
oops.. here's the email check...
frmvalidator.addValidation("emailinputboxname","email","email error message");

this script works on all browsers...
0
 

Author Comment

by:andreni78
ID: 11865664
also.. if you can also make the error message go next to the inputbox/selectbox/radio etc with users choice of font style.. that would be fantastic..(make it an available option with a different message)(definitely not priority)

(PRIORITY)and once the user enters in information corretly.. the inputbox/selectbox/radio will go back to normal rightaway without clicking anywhere...

i know i'm asking a lot but this will make the best  javascript validation script ever known to man! =)

if you want to add any suggestions.. it is definitely welcomed...
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 11866123
Extend this function:

function vdesc_validate(){
  if(!validateInput(this.desc,this.itemobj,this.error)){
    this.itemobj.oldColor = this.itemobj.style.backgroundColor;
    this.itemobj.style.backgroundColor="yellow"
    this.itemobj.focus();
    this.itemobj.onkeydown = function(){this.style.backgroundColor=this.oldColor};
    this.itemobj.onclick = this.itemobj.onkeydown;
    return false;
  } else {
    this.itemobj.style.backgroundColor=this.itemobj.oldColor;
    return true;
  }
}


0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 

Author Comment

by:andreni78
ID: 11866138
hmm i see.. so i can add anything within that function.. but still.. it only checks one at a time.. it doesn't show multiple error inputs
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 11866149
Do you want me to rewrite the whole garbage! No thanks ;-)
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 11866210
Ok, perhaps this helps a bit:

function form_submit_handler(){
    var retVal = true;
    for(var itr=0;itr < this.elements.length;itr++)
    {
         if(this.elements[itr].validationset &&
       !this.elements[itr].validationset.validate())
         {
           retVal = false;
         }
    }
    if(retVal && this.addnlvalidation)
    {
      str =" var ret = "+this.addnlvalidation+"()";
      eval(str);
   if(retVal && !ret) return ret;
    }
    return retVal;
}

0
 

Author Comment

by:andreni78
ID: 11866391
whoa.. so many alerts @_@ .. i had like 20 alerts with that.. but it's getting there!
0
 

Author Comment

by:andreni78
ID: 11866414
also if you could make the text color changeable too.. once that's solved.. u definitely deserve your 500...
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 11866416
You asked for that ;-)

I can guess what you will ask next: How about collecting the messig lines to one alert(;-)

0
 
LVL 63

Expert Comment

by:Zvonko
ID: 11866421
The color changes is already implemeted in the vdesc_validate() function, isn't it?
0
 
LVL 63

Accepted Solution

by:
Zvonko earned 500 total points
ID: 11866473
Check wether this version does help you:

<html>
<head>
<script>

function Validator(frmname){
   this.formobj=document.forms[frmname];
    if(!this.formobj)
    {
      alert("BUG: couldnot get Form object "+frmname);
         return;
    }
    if(this.formobj.onsubmit)
    {
     this.formobj.old_onsubmit = this.formobj.onsubmit;
     this.formobj.onsubmit=null;
    }
    else
    {
     this.formobj.old_onsubmit = null;
    }
    this.formobj.onsubmit=form_submit_handler;
    this.addValidation = add_validation;
    this.setAddnlValidationFunction=set_addnl_vfunction;
    this.clearAllValidations = clear_all_validations;
}
function set_addnl_vfunction(functionname)
{
 this.formobj.addnlvalidation = functionname;
}
function clear_all_validations()
{
    for(var itr=0;itr < this.formobj.elements.length;itr++)
    {
         this.formobj.elements[itr].validationset = null;
    }
}
var errMsg;
function form_submit_handler(){
    errMsg = "";
    var retVal = true;
    for(var itr=0;itr < this.elements.length;itr++)
    {
         if(this.elements[itr].validationset &&
       !this.elements[itr].validationset.validate())
         {
           retVal = false;
         }
    }
   if(errMsg>""){
     alert("Correct this errors:"+errMsg);
     return false;
   }
   if(retVal && this.addnlvalidation)
    {
      str =" var ret = "+this.addnlvalidation+"()";
      eval(str);
   if(retVal && !ret) return ret;
   }
   return retVal;
}
function add_validation(itemname,descriptor,errstr)
{
    if(!this.formobj)
    {
         alert("BUG: the form object is not set properly");
         return;
    }//if
    var itemobj = this.formobj[itemname];

   if(itemobj.length && isNaN(itemobj.selectedIndex) )
   //for radio button; don't do for 'select' item
    {
         itemobj = itemobj[0];
    }    
     if(!itemobj)
    {
         alert("BUG: Couldnot get the input object named: "+itemname);
         return;
    }
   
     if(!itemobj.validationset)
    {
         itemobj.validationset = new ValidationSet(itemobj);
    }
    itemobj.validationset.add(descriptor,errstr);
}
function ValidationDesc(inputitem,desc,error)
{
   this.desc=desc;
    this.error=error;
    this.itemobj = inputitem;
    this.validate=vdesc_validate;
}
function vdesc_validate(){
  if(!validateInput(this.desc,this.itemobj,this.error)){
    this.itemobj.oldColor = this.itemobj.style.backgroundColor;
    this.itemobj.style.backgroundColor="yellow"
    this.itemobj.focus();
    this.itemobj.onkeydown = function(){this.style.backgroundColor=this.oldColor};
    this.itemobj.onclick = this.itemobj.onkeydown;
    return false;
  } else {
    this.itemobj.style.backgroundColor=this.itemobj.oldColor;
    return true;
  }
}
function ValidationSet(inputitem)
{
   this.vSet=new Array();
    this.add= add_validationdesc;
    this.validate= vset_validate;
    this.itemobj = inputitem;
}
function add_validationdesc(desc,error)
{
 this.vSet[this.vSet.length]=
  new ValidationDesc(this.itemobj,desc,error);
}
function vset_validate()
{
   for(var itr=0;itr<this.vSet.length;itr++)
      {
        if(!this.vSet[itr].validate())
           {
             return false;
           }
      }
      return true;
}

/*  checks the validity of an email address entered
*   returns true or false
*/
function validateEmail(email)
{
   var splitted = email.match("^(.+)@(.+)$");
   if(splitted == null) return false;
   if(splitted[1] != null )
   {
     var regexp_user=/^\"?[\w-_\.]*\"?$/;
     if(splitted[1].match(regexp_user) == null) return false;
   }
   if(splitted[2] != null)
   {
     var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
     if(splitted[2].match(regexp_domain) == null)
      {
        var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
        if(splitted[2].match(regexp_ip) == null) return false;
     }// if
     return true;
   }
return false;
}

function TestComparison(objValue,strCompareElement,strvalidator,strError)
{
  var bRet=true;
  var objCompare=null;
  if(!objValue.form)
  {
     alert("BUG: No Form object!");
      return false
  }
  objCompare = objValue.form.elements[strCompareElement];
  if(!objCompare)
  {
    alert("BUG: Element with name"+strCompareElement+" not found !");
    return false;
  }
  if(strvalidator != "eqelmnt" &&
         strvalidator != "neelmnt")
  {
     if(isNaN(objValue.value))
      {
        errMsg += "\n\t"+objValue.name+": Should be a number ";
        return false;
      }//if
      if(isNaN(objCompare.value))
      {
        errMsg += "\n\t"+objCompare.name+": Should be a number ";
        return false;
      }//if        
  }//if
  var cmpstr="";
  switch(strvalidator)
  {
      case "eqelmnt":
               {
                 if(objValue.value != objCompare.value)
                 {
                      cmpstr = " should be equal to ";
                    bRet = false;
                 }//if
                 break;
              }//case
         case "ltelmnt":
              {
              if(eval(objValue.value) >= eval(objCompare.value))
                    {
                     cmpstr =  " should be less than ";
                      bRet = false;                        
                    }
                break;
              }//case
         case "leelmnt":
              {
                   if(eval(objValue.value) >  eval(objCompare.value))
                    {
                     cmpstr =  " should be less than or equal to";
                      bRet = false;                        
                    }
                break;
              }//case          
         case "gtelmnt":
              {
                   if(eval(objValue.value) <=  eval(objCompare.value))
                    {
                     cmpstr =  " should be greater than";
                      bRet = false;                        
                    }
                break;
              }//case
         case "geelmnt":
              {
                   if(eval(objValue.value) < eval(objCompare.value))
                    {
                     cmpstr =  " should be greater than or equal to";
                      bRet = false;                        
                    }
                break;
              }//case
         case "neelmnt":
              {
                 if(objValue.value.length > 0 &&
                   objCompare.value.length > 0 &&
                   objValue.value == objCompare.value)
                 {
                      cmpstr = " should be different from ";
                    bRet = false;
                 }//if
                 break;              
               }              
   }//switch
  if(bRet==false)
  {
     if(!strError || strError.length==0)
      {
        strError = objValue.name + cmpstr + objCompare.value;
       }//if
      errMsg += "\n\t"+strError;
  }//if
  return bRet;
}
function TestSelMin(objValue,strMinSel,strError)
{
   var bret = true;
    var objcheck = objValue.form.elements[objValue.name];
    var chkcount =0;
    if(objcheck.length)
    {
         for(var c=0;c < objcheck.length;c++)
         {
            if(objcheck[c].checked == "1")
            {
              chkcount++;
            }//if
         }//for
    }
    else
    {
      chkcount = (objcheck.checked == "1")?1:0;
    }
    var minsel = eval(strMinSel);
    if(chkcount < minsel)
    {
         if(!strError || strError.length ==0)
          {
               strError = "Please Select atleast"+minsel+" check boxes for"+objValue.name;  
         }//if                                                              
          errMsg += "\n\t"+strError;
          bret = false;
    }
    return bret;
}

function TestDontSelectChk(objValue,chkValue,strError)
{
   var pass=true;
    var objcheck = objValue.form.elements[objValue.name];
   if(objcheck.length)
    {
         var idxchk=-1;
         for(var c=0;c < objcheck.length;c++)
         {
            if(objcheck[c].value == chkValue)
            {
              idxchk=c;
               break;
            }//if
         }//for
         if(idxchk>= 0)
         {
           if(objcheck[idxchk].checked=="1")
           {
             pass=false;
           }
         }//if
    }
    else
    {
         if(objValue.checked == "1")
         {
              pass=false;
         }//if
    }//else
    if(pass==false)
    {
    if(!strError || strError.length ==0)
        {
             strError = "Can't Proceed as you selected "+objValue.name;  
       }//if                
       errMsg += "\n\t"+strError;
     
     }
   return pass;
}

function TestRequiredInput(objValue,strError)
{
var ret = true;
   if(eval(objValue.value.length) == 0)
    {
       if(!strError || strError.length ==0)
       {
         strError = objValue.name + " : Required Field";
       }//if
       errMsg += "\n\t"+strError;
       ret=false;
    }//if
return ret;
}

function TestMaxLen(objValue,strMaxLen,strError)
{
var ret = true;
   if(eval(objValue.value.length) > eval(strMaxLen))
    {
      if(!strError || strError.length ==0)
      {
        strError = objValue.name + " : "+ strMaxLen +" characters maximum ";
      }//if
      errMsg += "\n\t"+strError + "\n\t[Current length = " + objValue.value.length + " ]";
      ret = false;
    }//if
return ret;
}

function TestMinLen(objValue,strMinLen,strError)
{
var ret = true;
   if(eval(objValue.value.length) <  eval(strMinLen))
    {
      if(!strError || strError.length ==0)
      {
        strError = objValue.name + " : " + strMinLen + " characters minimum  ";
      }//if              
      errMsg += "\n\t"+strError + "\n\t[Current length = " + objValue.value.length + " ]";
      ret = false;  
    }//if
return ret;
}

function TestInputType(objValue,strRegExp,strError,strDefaultError)
{
  var ret = true;

   var charpos = objValue.value.search(strRegExp);
    if(objValue.value.length > 0 &&  charpos >= 0)
    {
     if(!strError || strError.length ==0)
      {
        strError = strDefaultError;
     }//if
      errMsg += "\n\t"+strError + "\n\t [Error character position " + eval(charpos+1)+"]";
      ret = false;
    }//if
 return ret;
}

function TestEmail(objValue,strError)
{
var ret = true;
    if(objValue.value.length > 0 && !validateEmail(objValue.value)      )
     {
       if(!strError || strError.length ==0)
       {
          strError = objValue.name+": Enter a valid Email address ";
       }//if                                              
       errMsg += "\n\t"+strError;
       ret = false;
     }//if
return ret;
}

function TestLessThan(objValue,strLessThan,strError)
{
var ret = true;
      if(isNaN(objValue.value))
       {
         errMsg += "\n\t"+objValue.name+": Should be a number ";
         ret = false;
       }//if
       else
      if(eval(objValue.value) >=  eval(strLessThan))
       {
         if(!strError || strError.length ==0)
         {
           strError = objValue.name + " : value should be less than "+ strLessThan;
         }//if              
         errMsg += "\n\t"+strError;
         ret = false;                
        }//if  
return ret;          
}

function TestGreaterThan(objValue,strGreaterThan,strError)
{
var ret = true;
    if(isNaN(objValue.value))
     {
       errMsg += "\n\t"+objValue.name+": Should be a number ";
       ret = false;
     }//if
      else
    if(eval(objValue.value) <=  eval(strGreaterThan))
      {
        if(!strError || strError.length ==0)
        {
          strError = objValue.name + " : value should be greater than "+ strGreaterThan;
        }//if              
        errMsg += "\n\t"+strError;  
       ret = false;
     }//if  
return ret;          
}

function TestRegExp(objValue,strRegExp,strError)
{
var ret = true;
   if( objValue.value.length > 0 && 
        !objValue.value.match(strRegExp) )
    {
      if(!strError || strError.length ==0)
      {
        strError = objValue.name+": Invalid characters found ";
      }//if                                                              
      errMsg += "\n\t"+strError;
      ret = false;                  
    }//if
return ret;
}
function TestDontSelect(objValue,index,strError)
{
var ret = true;
    if(objValue.selectedIndex == null)
     {
       alert("BUG: dontselect command for non-select Item");
       ret = false;
     }
      else
    if(objValue.selectedIndex == eval(index))
     {
      if(!strError || strError.length ==0)
       {
       strError = objValue.name+": Please Select one option ";
       }//if                                                              
       errMsg += "\n\t"+strError;
       ret =  false;                                  
      }
return ret;
}

function TestSelectOneRadio(objValue,strError)
{
    var objradio = objValue.form.elements[objValue.name];
    var one_selected=false;
    for(var r=0;r < objradio.length;r++)
    {
      if(objradio[r].checked == "1")
      {
           one_selected=true;
         break;
      }
    }
    if(false == one_selected)
    {
     if(!strError || strError.length ==0)
       {
        strError = "Please select one option from "+objValue.name;
       }    
       errMsg += "\n\t"+strError;
    }
return one_selected;
}

//*  Checks each field in a form
function validateInput(strValidateStr,objValue,strError)
{
    var ret = true;
   var epos = strValidateStr.search("=");
    var  command  = "";
    var  cmdvalue = "";
    if(epos >= 0)
    {
     command  = strValidateStr.substring(0,epos);
     cmdvalue = strValidateStr.substr(epos+1);
    }
    else
    {
     command = strValidateStr;
    }

    switch(command)
    {
        case "req":
        case "required":
         {
             ret = TestRequiredInput(objValue,strError)
          break;            
         }
       case "maxlength":
        case "maxlen":
          {
                ret = TestMaxLen(objValue,cmdvalue,strError)
            break;
          }
       case "minlength":
        case "minlen":
           {
                ret = TestMinLen(objValue,cmdvalue,strError)
            break;
           }
       case "alnum":
        case "alphanumeric":
           {
                    ret = TestInputType(objValue,"[^A-Za-z0-9]",strError,
                              objValue.name+": Only alpha-numeric characters allowed ");
                   break;
           }
       case "alnum_s":
        case "alphanumeric_space":
           {
                    ret = TestInputType(objValue,"[^A-Za-z0-9\\s]",strError,
                              objValue.name+": Only alpha-numeric characters and space allowed ");
                   break;
           }            
        case "num":
        case "numeric":
           {
                ret = TestInputType(objValue,"[^0-9]",strError,
                              objValue.name+": Only digits allowed ");
               break;              
           }
       case "alphabetic":
        case "alpha":
           {
                ret = TestInputType(objValue,"[^A-Za-z]",strError,
                              objValue.name+": Only alphabetic characters allowed ");
               break;
           }
       case "alphabetic_space":
        case "alpha_s":
           {
                ret = TestInputType(objValue,"[^A-Za-z\\s]",strError,
                              objValue.name+": Only alphabetic characters and space allowed ");
               break;
           }
       case "email":
          {
                  ret = TestEmail(objValue,strError);
              break;
          }
       case "lt":
        case "lessthan":
         {
               ret = TestLessThan(objValue,cmdvalue,strError);
             break;
         }
       case "gt":
        case "greaterthan":
         {
               ret = TestGreaterThan(objValue,cmdvalue,strError);
           break;
         }
       case "regexp":
         {
               ret = TestRegExp(objValue,cmdvalue,strError);
          break;
         }
       case "dontselect":
         {
                ret = TestDontSelect(objValue,cmdvalue,strError)
            break;
         }
         case "dontselectchk":
         {
              ret = TestDontSelectChk(objValue,cmdvalue,strError)
              break;
         }
         case "selmin":
         {
              ret = TestSelMin(objValue,cmdvalue,strError);
              break;
         }
         case "selone":
         {
              ret = TestSelectOneRadio(objValue,strError);
             break;
         }          
          //Comparisons
         case "eqelmnt":
          case "ltelmnt":
         case "leelmnt":
         case "gtelmnt":
         case "geelmnt":
         case "neelmnt":
         {
             return TestComparison(objValue,cmdvalue,command,strError);
             break;
         }
   }//switch
    return ret;
}
</script>
</head>
<body>
and here's how it's currently implemented:
after the form:

<form name="myform">
<select name="name1">
<option>One
<option>Two
<option>Three
</select>
<input type=text name="name2">
<input type=text name="name3">
<input type=radio name="name4" value="One"> One
<input type=radio name="name4" value="Two"> Two
<input type=radio name="name4" value="Three"> Three
<input type=checkbox name="name5" value="One"> One
<input type=checkbox name="name5" value="Two"> Two
<input type=checkbox name="name5" value="Three"> Three
<input type=submit>
</form>

<SCRIPT language=JavaScript type="text/javascript">
 var frmvalidator  = new Validator("myform");
<!-- for select list form, uses "dontselect=0" -->
 frmvalidator.addValidation("name1","dontselect=0","Select list error message");
<!-- "req" is for required entry for inputbox -->
 frmvalidator.addValidation("name2","req","inputbox error message");
<!-- "minlen=#" is minimum length requirement -->
 frmvalidator.addValidation("name3","minlen=3", "inputbox minimum length error message");
<!-- "selone" is for radio box requirement selection -->
 frmvalidator.addValidation("name4","selone","Radio box error message");
<!-- "selmin" is for checkbox requirement -->
 frmvalidator.addValidation("name5","selmin=1","checkbox error message");
</script>
</body>
</html>

0
 

Author Comment

by:andreni78
ID: 11866551
WOW.. thanks! it works!

but a bug.. if the user hits submits twice with errors.. the "yellow" color becomes oldColor.. so oldColor must be set to a variable..

also I asked about changing the TEXT color as a custom error color..  not the background color.. in response to your post =)

"The color changes is already implemeted in the vdesc_validate() function, isn't it?"

Absolutely fantastic job...
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 11866574
How about this color version:

function vdesc_validate(){
  if(!this.itemobj.oldColor){
    this.itemobj.oldColor = "color:"+this.itemobj.style.backgroundColor;
  }
  if(!validateInput(this.desc,this.itemobj,this.error)){
    this.itemobj.style.backgroundColor="yellow"
    this.itemobj.focus();
    this.itemobj.onkeydown = function(){this.style.backgroundColor=this.oldColor.split("color:")[1]};
    this.itemobj.onclick = this.itemobj.onkeydown;
    return false;
  } else {
    this.itemobj.style.backgroundColor=this.itemobj.oldColor.split("color:")[1];
    return true;
  }
}

0
 
LVL 63

Expert Comment

by:Zvonko
ID: 11866578
It is getting late for me. I have to go to bed.

Good Night!
Zvonko

0
 

Author Comment

by:andreni78
ID: 11867073
u've put in a lot of hard work already.. i'll post up another requesting some bug fixes... thanks Zvonko!
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 11868331
You are welcome.
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article, we'll look how to sort an Array in JavaScript, including the more advanced techniques of sorting a collection of records either ascending or descending on two or more fields. Basic Sorting of Arrays First, let's look at the …
In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question