andreni78
asked on
Validation Script Bug Fixes and Add a feature...
This script doesn't place the cursor to the top most input box/select box/radio/checkbox that has error.. also the text in the input field doesn't change to a custom color.. like white text on red background if there's an error in the particular input field..
if someone can add that and fix the bug.. that would be great.. before it would put the cursor on the top most input field.. but not this time..
i will display the script and it's usage in the next post...
if someone can add that and fix the bug.. that would be great.. before it would put the cursor on the top most input field.. but not this time..
i will display the script and it's usage in the next post...
I have modified only 'form_submit_handler' method. Replace your existing method with the modified one and check if it solves ur purpose.
function form_submit_handler(){
errMsg = "";
var retVal = true;
var firstFrmValidateFailedObj;
for(var itr=0;itr < this.elements.length;itr++ )
{
if(this.elements[itr].vali dationset && !this.elements[itr].valida tionset.va lidate())
{
retVal = false;
if(typeof(firstFrmValidate FailedObj) == "undefined"){
firstFrmValidateFailedObj = this.elements[itr];
}
}
}
if(errMsg>""){
alert("Please correct these errors:"+errMsg);
if(typeof(firstFrmValidate FailedObj) != "undefined"){
if(firstFrmValidateFailedO bj.type == "text" || firstFrmValidateFailedObj. type == "textarea"){
firstFrmValidateFailedObj. select();
}
firstFrmValidateFailedObj. focus();
}
return false;
}
if(retVal && this.addnlvalidation){
str =" var ret = "+this.addnlvalidation+"() ";
eval(str);
if(retVal && !ret) return ret;
}
return retVal;
}
function form_submit_handler(){
errMsg = "";
var retVal = true;
var firstFrmValidateFailedObj;
for(var itr=0;itr < this.elements.length;itr++
{
if(this.elements[itr].vali
{
retVal = false;
if(typeof(firstFrmValidate
firstFrmValidateFailedObj = this.elements[itr];
}
}
}
if(errMsg>""){
alert("Please correct these errors:"+errMsg);
if(typeof(firstFrmValidate
if(firstFrmValidateFailedO
firstFrmValidateFailedObj.
}
firstFrmValidateFailedObj.
}
return false;
}
if(retVal && this.addnlvalidation){
str =" var ret = "+this.addnlvalidation+"()
eval(str);
if(retVal && !ret) return ret;
}
return retVal;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You script is a bit messy, I'd have to say. Is it ok if I change it to this:?
var errMsg="";
var formobj=false;
function Validator(frmname) {
formobj=document.forms[frm name];
if(!formobj) {
alert("Could not get form object "+frmname+". Please try again.");
return false;
} else {
for (var i=0;i<addValidation.length ;i++) {
alert(i);
validateInput(addValidatio n[i].split (","));
}
if (errMsg!="") {
return false;
}
}
return true;
}
function validateInput(elArray) {
ret=true;
if (!formobj.elements[elArray [0]]) {
return false;
} else {
currEl=formobj.elements[el Array[0]];
}
if (elArray[1]) {
epos=elArray[1].search("=" );
} else {
return true;
}
command="";
cmdvalue="";
if (epos>=0) {
command=elArray[1].substri ng(0,epos) ;
cmdvalue=elArray[1].substr (epos+1);
} else {
command=elArray[1];
}
strErr=(elArray[2]) ? elArray[2] : "An Unspecified Error Occurred";
switch(command) {
case "req":
case "required":
ret=TestRequiredInput(curr El,strErr) ;
break;
case "maxlength":
case "maxlen":
ret=TestLen(currEl,command ,cmdvalue, strErr)
break;
case "minlength":
case "minlen":
ret=TestLen(currEl,command ,cmdvalue, strErr)
break;
case "alnum":
case "alphanumeric":
ret=TestInputType(currEl," [^A-Za-z0- 9]",strErr ,currEl.na me+": Only alpha-numeric characters allowed!");
break;
case "alnum_s":
case "alphanumeric_space":
ret=TestInputType(currEl," [^A-Za-z0- 9\\s]",str Err,currEl .name+": Only alpha-numeric characters and spaces allowed!");
break;
case "num":
case "numeric":
ret=TestInputType(currEl," \D",strErr ,currEl.na me+": Only digits allowed!");
break;
case "alphabetic":
case "alpha":
ret=TestInputType(objValue ,"[^A-Za-z ]",strErr, currEl.nam e+": Only alphabetic characters allowed!");
break;
case "alphabetic_space":
case "alpha_s":
ret=TestInputType(currEl," [^A-Za-z\\ s]",strErr ,currEl.na me+": Only alphabetic characters and space allowed!");
break;
case "email":
ret=validateEmail(currEl,s trErr);
break;
case "lt":
case "lessthan":
ret=TestInequality(currEl, command,cm dvalue,str Err);
break;
case "gt":
case "greaterthan":
ret=TestInequality(currEl, command,cm dvalue,str Err);
break;
case "regexp":
ret=TestRegExp(currEl,cmdv alue);
break;
case "dontselect":
ret = TestDontSelect(currEl,cmdv alue,strEr r)
break;
case "dontselectchk":
ret=TestDontSelectChk(curr El,cmdvalu e,strErr)
break;
case "selmin":
ret=TestSelMin(currEl,cmdv alue,strEr r);
break;
case "selone":
ret=TestSelectOneRadio(cur rEl,strErr );
break;
///Comparisons//////////// ////////// ////////// ////////// //////////
case "eqelmnt":
case "ltelmnt":
case "leelmnt":
case "gtelmnt":
case "geelmnt":
case "neelmnt":
ret=TestComparison(currEl, cmdvalue,c ommand,str Err);
break;
default:
ret=false;
break;
}
return ret;
}
function validateEmail(obj,strError ) {
email=obj.value
if (email.match("^[a-zA-Z][\w \.-]*[a-zA -Z0-9]@[a- zA-Z0-9][\ w\.-]*[a-z A-Z0-9]\.[ a-zA-Z][a- zA-Z\.]*[a -zA-Z]$")! =null) {
return true;
}
changeAppearance(obj,"whit e","red");
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
return false;
}
function TestRequiredInput(obj,strE rror) {
objValue=obj.value;
if (objValue.length==0) {
if (!strError||strError.lengt h==0) {
strError=obj.name+": Required Field!";
}
changeAppearance(obj,"whit e","red");
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
return false;
}
return true;
}
function TestLen(obj,com,strLen,str Error) {
objValue=obj.value;
ret=true;
switch(com) {
case "maxlength":
case "maxlen":
if (objValue.length>strLen) {
ret=false;
}
break;
case "minlength":
case "minlen":
if (objValue.length<strLen) {
ret=false;
}
break;
default:
alert("Program Error:\nUnrecognized value passed to TestLen function!");
break;
}
if (!ret) {
changeAppearance(obj,"whit e","red");
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
return ret;
}
return ret;
}
function TestInputType(obj,strRegEx p,strError ,strDefaul tError) {
objValue=obj.value;
var charpos=objValue.search(st rRegExp);
if (strError&&(!strError.sear ch("^\s+$" ))) {
strDefaultError=strError;
}
if(charpos>=0) {
changeAppearance(obj,"whit e","red");
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n\t[Err or at character position "+charpos+"]\n";
return false;
}
return true;
}
function TestInequality(obj,com,num Comp,strEr ror) {
ret=true;
objValue=obj.value;
if(isNaN(objValue.value)) {
if (!strError||strError.lengt h==0) {
strError+="\n\t"+obj.name+ ": Should be a number!";
}
ret=false;
} else {
switch(com) {
case "lt":
case "lessthan":
case "ltelmnt":
if (objValue>=parseInt(numCom p,10)) {
if (!strError||strError.lengt h==0) {
strError=obj.name+": value should be less than "+numComp;
}
ret=false;
}
break;
case "gt":
case "greaterthan":
case "gtelmnt":
if (objValue<=parseInt(numCom p,10)) {
if (!strError||strError.lengt h==0) {
strError=obj.name+": value should be greater than "+numComp;
}
ret=false;
}
break;
case "leelmnt":
if (objValue>parseInt(numComp ,10)) {
if (!strError||strError.lengt h==0) {
strError=obj.name+": value should be less than or equal to "+numComp;
}
}
break;
case "geelmnt":
if (objValue<parseInt(numComp ,10)) {
if (!strError||strError.lengt h==0) {
strError=obj.name+": value should be greater than or equal to "+numComp;
}
}
break;
default:
alert("Program Error:\nUnrecognized value passed to TestInequality function!");
break;
}
if (!ret) {
changeAppearance(obj,"whit e","red");
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
}
}
return ret;
}
function TestRegExp(obj,strRegExp) {
strError="";
objValue=obj.value;
if (!objValue.value.match(str RegExp.toS tring())) {
strError=obj.name+": Invalid characters found!";
}
errMsg+=strError;
if (strError!="") {
changeAppearance(obj,"whit e","red");
if (errMsg=="") {
obj.focus();
}
errMsg+="\n";
return false;
}
return true;
}
function TestComparison(obj,strComp areElement ,strvalida tor,strErr or) {
objValue=obj.value;
ret=true;
var objCompare=null;
objCompare=obj.form.elemen ts[strComp areElement ];
if(!objCompare) {
alert("Element with name"+strCompareElement+" not found!");
return false;
}
objCompareVal=objCompare.v alue;
if(strvalidator=="leelmnt" ||strvalid ator=="gee lmnt"||str validator= ="gtelmnt" ||strvalid ator=="lte lmnt") {
return(TestInequality(obj, strvalidat or,objComp areVal,str Error));
}
switch(strvalidator) {
case "eqelmnt":
if (objValue!=objCompareVal) {
if (!strError||strError.lengt h==0) {
strError=obj.name+" should be equivalent to "+objCompare.name;
}
ret=false;
}
break;
case "neelmnt":
if (objValue==objCompareVal) {
if (!strError||strError.lengt h==0) {
strError=obj.name+" should be different from "+objCompare.name;
}
ret = false;
}
break;
default:
alert("Program Error:\nUnrecognized value passed to TestComparison function!");
break;
}
if(!ret) {
changeAppearance(obj,"whit e","red");
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
}
return ret;
}
function TestSelMin(obj,strMinSel,s trError) {
var objcheck=obj.form.elements [obj.name] ;
var chkcount=0;
for (var i=0;i<objcheck.length;i++) {
if(objcheck[i].checked=="1 ") {
chkcount++;
}
}
if(chkcount<parseInt(strMi nSel,10)) {
if (!strError||strError.lengt h==0) {
strError="Please Select at least "+minsel+" check boxes with name "+obj.name+"!";
}
changeAppearance(obj,"whit e","red");
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
return false;
}
return true;
}
function TestDontSelectChk(obj,chkV alue,strEr ror) {
ret=true;
if(obj.length) {
var idxchk=-1;
for (var i=0;i<obj.length;i++) {
if(obj[c].value==chkValue) {
idxchk=c;
break;
}
}
if(idxchk!=-1) {
if(obj[idxchk].checked) {
ret=false;
}
}
} else {
if (obj.checked) {
ret=false;
}
}
if(!ret) {
if (!strError||strError.lengt h==0) {
strError="Can't Proceed as you selected "+obj.name;
}
changeAppearance(obj,"whit e","red");
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
}
return ret;
}
function TestDontSelect(obj,index,s trError) {
ret = true;
if (obj.selectedIndex==parseI nt(index,1 0)) {
ret = false;
if (!strError||strError.lengt h==0) {
strError = obj.name+": Please don't select option "+index+"!";
}
changeAppearance(obj,"whit e","red");
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
}
return ret;
}
function TestSelectOneRadio(obj,str Error) {
ret=false;
for (var i=0;i<obj.length;i++) {
if (obj[i].checked) {
ret=true;
break;
}
}
if (!ret) {
if (!strError||strError.lengt h==0) {
strError = "Please select one option from "+obj.name;
}
errMsg+=strError+"\n";
}
return ret;
}
function changeAppearance(obj,fgcol ,bgcol) {
obj.style.backgroundColor= bgcol;
obj.style.color=fgcol;
}
These functions are changed slightly and may have slighly different functions than you want. Usage is follows:
You can have those functions in an external js or on your page. On your page, also have this in the <head>:
<script language="javascript">
<!--
var addValidation = new Array;
addValidation[0]="name1,do ntselect=0 ,Select list error message";
addValidation[1]="name2,re q,inputbox error message";
addValidation[2]="name3,mi nlen=3,inp utbox minimum length error message";
//-->
</script>
where you set the validations as such separated by comma.
Finally, in your form tag, have this:
<form name="myform" onsubmit="return(Validator ('myform') );">
var errMsg="";
var formobj=false;
function Validator(frmname) {
formobj=document.forms[frm
if(!formobj) {
alert("Could not get form object "+frmname+". Please try again.");
return false;
} else {
for (var i=0;i<addValidation.length
alert(i);
validateInput(addValidatio
}
if (errMsg!="") {
return false;
}
}
return true;
}
function validateInput(elArray) {
ret=true;
if (!formobj.elements[elArray
return false;
} else {
currEl=formobj.elements[el
}
if (elArray[1]) {
epos=elArray[1].search("="
} else {
return true;
}
command="";
cmdvalue="";
if (epos>=0) {
command=elArray[1].substri
cmdvalue=elArray[1].substr
} else {
command=elArray[1];
}
strErr=(elArray[2]) ? elArray[2] : "An Unspecified Error Occurred";
switch(command) {
case "req":
case "required":
ret=TestRequiredInput(curr
break;
case "maxlength":
case "maxlen":
ret=TestLen(currEl,command
break;
case "minlength":
case "minlen":
ret=TestLen(currEl,command
break;
case "alnum":
case "alphanumeric":
ret=TestInputType(currEl,"
break;
case "alnum_s":
case "alphanumeric_space":
ret=TestInputType(currEl,"
break;
case "num":
case "numeric":
ret=TestInputType(currEl,"
break;
case "alphabetic":
case "alpha":
ret=TestInputType(objValue
break;
case "alphabetic_space":
case "alpha_s":
ret=TestInputType(currEl,"
break;
case "email":
ret=validateEmail(currEl,s
break;
case "lt":
case "lessthan":
ret=TestInequality(currEl,
break;
case "gt":
case "greaterthan":
ret=TestInequality(currEl,
break;
case "regexp":
ret=TestRegExp(currEl,cmdv
break;
case "dontselect":
ret = TestDontSelect(currEl,cmdv
break;
case "dontselectchk":
ret=TestDontSelectChk(curr
break;
case "selmin":
ret=TestSelMin(currEl,cmdv
break;
case "selone":
ret=TestSelectOneRadio(cur
break;
///Comparisons////////////
case "eqelmnt":
case "ltelmnt":
case "leelmnt":
case "gtelmnt":
case "geelmnt":
case "neelmnt":
ret=TestComparison(currEl,
break;
default:
ret=false;
break;
}
return ret;
}
function validateEmail(obj,strError
email=obj.value
if (email.match("^[a-zA-Z][\w
return true;
}
changeAppearance(obj,"whit
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
return false;
}
function TestRequiredInput(obj,strE
objValue=obj.value;
if (objValue.length==0) {
if (!strError||strError.lengt
strError=obj.name+": Required Field!";
}
changeAppearance(obj,"whit
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
return false;
}
return true;
}
function TestLen(obj,com,strLen,str
objValue=obj.value;
ret=true;
switch(com) {
case "maxlength":
case "maxlen":
if (objValue.length>strLen) {
ret=false;
}
break;
case "minlength":
case "minlen":
if (objValue.length<strLen) {
ret=false;
}
break;
default:
alert("Program Error:\nUnrecognized value passed to TestLen function!");
break;
}
if (!ret) {
changeAppearance(obj,"whit
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
return ret;
}
return ret;
}
function TestInputType(obj,strRegEx
objValue=obj.value;
var charpos=objValue.search(st
if (strError&&(!strError.sear
strDefaultError=strError;
}
if(charpos>=0) {
changeAppearance(obj,"whit
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n\t[Err
return false;
}
return true;
}
function TestInequality(obj,com,num
ret=true;
objValue=obj.value;
if(isNaN(objValue.value)) {
if (!strError||strError.lengt
strError+="\n\t"+obj.name+
}
ret=false;
} else {
switch(com) {
case "lt":
case "lessthan":
case "ltelmnt":
if (objValue>=parseInt(numCom
if (!strError||strError.lengt
strError=obj.name+": value should be less than "+numComp;
}
ret=false;
}
break;
case "gt":
case "greaterthan":
case "gtelmnt":
if (objValue<=parseInt(numCom
if (!strError||strError.lengt
strError=obj.name+": value should be greater than "+numComp;
}
ret=false;
}
break;
case "leelmnt":
if (objValue>parseInt(numComp
if (!strError||strError.lengt
strError=obj.name+": value should be less than or equal to "+numComp;
}
}
break;
case "geelmnt":
if (objValue<parseInt(numComp
if (!strError||strError.lengt
strError=obj.name+": value should be greater than or equal to "+numComp;
}
}
break;
default:
alert("Program Error:\nUnrecognized value passed to TestInequality function!");
break;
}
if (!ret) {
changeAppearance(obj,"whit
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
}
}
return ret;
}
function TestRegExp(obj,strRegExp) {
strError="";
objValue=obj.value;
if (!objValue.value.match(str
strError=obj.name+": Invalid characters found!";
}
errMsg+=strError;
if (strError!="") {
changeAppearance(obj,"whit
if (errMsg=="") {
obj.focus();
}
errMsg+="\n";
return false;
}
return true;
}
function TestComparison(obj,strComp
objValue=obj.value;
ret=true;
var objCompare=null;
objCompare=obj.form.elemen
if(!objCompare) {
alert("Element with name"+strCompareElement+" not found!");
return false;
}
objCompareVal=objCompare.v
if(strvalidator=="leelmnt"
return(TestInequality(obj,
}
switch(strvalidator) {
case "eqelmnt":
if (objValue!=objCompareVal) {
if (!strError||strError.lengt
strError=obj.name+" should be equivalent to "+objCompare.name;
}
ret=false;
}
break;
case "neelmnt":
if (objValue==objCompareVal) {
if (!strError||strError.lengt
strError=obj.name+" should be different from "+objCompare.name;
}
ret = false;
}
break;
default:
alert("Program Error:\nUnrecognized value passed to TestComparison function!");
break;
}
if(!ret) {
changeAppearance(obj,"whit
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
}
return ret;
}
function TestSelMin(obj,strMinSel,s
var objcheck=obj.form.elements
var chkcount=0;
for (var i=0;i<objcheck.length;i++)
if(objcheck[i].checked=="1
chkcount++;
}
}
if(chkcount<parseInt(strMi
if (!strError||strError.lengt
strError="Please Select at least "+minsel+" check boxes with name "+obj.name+"!";
}
changeAppearance(obj,"whit
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
return false;
}
return true;
}
function TestDontSelectChk(obj,chkV
ret=true;
if(obj.length) {
var idxchk=-1;
for (var i=0;i<obj.length;i++) {
if(obj[c].value==chkValue)
idxchk=c;
break;
}
}
if(idxchk!=-1) {
if(obj[idxchk].checked) {
ret=false;
}
}
} else {
if (obj.checked) {
ret=false;
}
}
if(!ret) {
if (!strError||strError.lengt
strError="Can't Proceed as you selected "+obj.name;
}
changeAppearance(obj,"whit
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
}
return ret;
}
function TestDontSelect(obj,index,s
ret = true;
if (obj.selectedIndex==parseI
ret = false;
if (!strError||strError.lengt
strError = obj.name+": Please don't select option "+index+"!";
}
changeAppearance(obj,"whit
if (errMsg=="") {
obj.focus();
}
errMsg+=strError+"\n";
}
return ret;
}
function TestSelectOneRadio(obj,str
ret=false;
for (var i=0;i<obj.length;i++) {
if (obj[i].checked) {
ret=true;
break;
}
}
if (!ret) {
if (!strError||strError.lengt
strError = "Please select one option from "+obj.name;
}
errMsg+=strError+"\n";
}
return ret;
}
function changeAppearance(obj,fgcol
obj.style.backgroundColor=
obj.style.color=fgcol;
}
These functions are changed slightly and may have slighly different functions than you want. Usage is follows:
You can have those functions in an external js or on your page. On your page, also have this in the <head>:
<script language="javascript">
<!--
var addValidation = new Array;
addValidation[0]="name1,do
addValidation[1]="name2,re
addValidation[2]="name3,mi
//-->
</script>
where you set the validations as such separated by comma.
Finally, in your form tag, have this:
<form name="myform" onsubmit="return(Validator
Oops, I spent a few hours typing all of this and editing so it was a stale window, sorry
ASKER
wow zyloch.. i don't want to spend all that time for nothing.. please answer my other post and i'll give you what you deserve.. definitely 500 isn't enough..
ASKER
function Validator(frmname){
this.formobj=document.form
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
this.addValidation = add_validation;
this.setAddnlValidationFun
this.clearAllValidations = clear_all_validations;
}
function set_addnl_vfunction(functi
{
this.formobj.addnlvalidati
}
function clear_all_validations()
{
for(var itr=0;itr < this.formobj.elements.leng
{
this.formobj.elements[itr]
}
}
var errMsg;
function form_submit_handler(){
errMsg = "";
var retVal = true;
for(var itr=0;itr < this.elements.length;itr++
{
if(this.elements[itr].vali
!this.elements[itr].valida
{
retVal = false;
}
}
if(errMsg>""){
alert("Please correct these 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,de
{
if(!this.formobj)
{
alert("BUG: the form object is not set properly");
return;
}//if
var itemobj = this.formobj[itemname];
if(itemobj.length && isNaN(itemobj.selectedInde
//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(
}
function ValidationDesc(inputitem,d
{
this.desc=desc;
this.error=error;
this.itemobj = inputitem;
this.validate=vdesc_valida
}
function vdesc_validate(){
if(!this.itemobj.oldColor)
this.itemobj.oldColor = "color:"+this.itemobj.styl
}
if(!validateInput(this.des
this.itemobj.style.backgro
this.itemobj.focus();
this.itemobj.onkeydown =
function(){this.style.back
this.itemobj.onclick = this.itemobj.onkeydown;
return false;
} else {
this.itemobj.style.backgro
return true;
}
}
function ValidationSet(inputitem)
{
this.vSet=new Array();
this.add= add_validationdesc;
this.validate= vset_validate;
this.itemobj = inputitem;
}
function add_validationdesc(desc,er
{
this.vSet[this.vSet.length
new ValidationDesc(this.itemob
}
function vset_validate()
{
for(var itr=0;itr<this.vSet.length
{
if(!this.vSet[itr].validat
{
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(regex
}
if(splitted[2] != null)
{
var regexp_domain=/^[\w-\.]*\.
if(splitted[2].match(regex
{
var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{
if(splitted[2].match(regex
}// if
return true;
}
return false;
}
function TestComparison(objValue,st
{
var bRet=true;
var objCompare=null;
if(!objValue.form)
{
alert("BUG: No Form object!");
return false
}
objCompare = objValue.form.elements[str
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,strMin
{
var bret = true;
var objcheck = objValue.form.elements[obj
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
{
var pass=true;
var objcheck = objValue.form.elements[obj
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].checke
{
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
{
var ret = true;
if(eval(objValue.value.len
{
if(!strError || strError.length ==0)
{
strError = objValue.name + " : Required Field";
}//if
errMsg += "\n\t"+strError;
ret=false;
}//if
return ret;
}
function TestMaxLen(objValue,strMax
{
var ret = true;
if(eval(objValue.value.len
{
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,strMin
{
var ret = true;
if(eval(objValue.value.len
{
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,str
{
var ret = true;
var charpos = objValue.value.search(strR
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,strErro
{
var ret = true;
if(objValue.value.length > 0 && !validateEmail(objValue.va
{
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,strL
{
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,s
{
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,strReg
{
var ret = true;
if( objValue.value.length > 0 &&
!objValue.value.match(strR
{
if(!strError || strError.length ==0)
{
strError = objValue.name+": Invalid characters found ";
}//if
errMsg += "\n\t"+strError;
ret = false;
}//if
return ret;
}
function TestDontSelect(objValue,in
{
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(objValu
{
var objradio = objValue.form.elements[obj
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(strValidateS
{
var ret = true;
var epos = strValidateStr.search("=")
var command = "";
var cmdvalue = "";
if(epos >= 0)
{
command = strValidateStr.substring(0
cmdvalue = strValidateStr.substr(epos
}
else
{
command = strValidateStr;
}
switch(command)
{
case "req":
case "required":
{
ret = TestRequiredInput(objValue
break;
}
case "maxlength":
case "maxlen":
{
ret = TestMaxLen(objValue,cmdval
break;
}
case "minlength":
case "minlen":
{
ret = TestMinLen(objValue,cmdval
break;
}
case "alnum":
case "alphanumeric":
{
ret = TestInputType(objValue,"[^
objValue.name+": Only alpha-numeric characters allowed ");
break;
}
case "alnum_s":
case "alphanumeric_space":
{
ret = TestInputType(objValue,"[^
objValue.name+": Only alpha-numeric characters and space
allowed ");
break;
}
case "num":
case "numeric":
{
ret = TestInputType(objValue,"[^
objValue.name+": Only digits allowed ");
break;
}
case "alphabetic":
case "alpha":
{
ret = TestInputType(objValue,"[^
objValue.name+": Only alphabetic characters allowed ");
break;
}
case "alphabetic_space":
case "alpha_s":
{
ret = TestInputType(objValue,"[^
objValue.name+": Only alphabetic characters and space
allowed ");
break;
}
case "email":
{
ret = TestEmail(objValue,strErro
break;
}
case "lt":
case "lessthan":
{
ret = TestLessThan(objValue,cmdv
break;
}
case "gt":
case "greaterthan":
{
ret = TestGreaterThan(objValue,c
break;
}
case "regexp":
{
ret = TestRegExp(objValue,cmdval
break;
}
case "dontselect":
{
ret = TestDontSelect(objValue,cm
break;
}
case "dontselectchk":
{
ret = TestDontSelectChk(objValue
break;
}
case "selmin":
{
ret = TestSelMin(objValue,cmdval
break;
}
case "selone":
{
ret = TestSelectOneRadio(objValu
break;
}
//Comparisons
case "eqelmnt":
case "ltelmnt":
case "leelmnt":
case "gtelmnt":
case "geelmnt":
case "neelmnt":
{
return TestComparison(objValue,cm
break;
}
}//switch
return ret;
}
USAGE:
<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
<!-- "req" is for required entry for inputbox -->
frmvalidator.addValidation
<!-- "minlen=#" is minimum length requirement -->
frmvalidator.addValidation
<!-- "selone" is for radio box requirement selection -->
frmvalidator.addValidation
<!-- "selmin" is for checkbox requirement -->
frmvalidator.addValidation
</script>
</body>
</html>