Link to home
Start Free TrialLog in
Avatar of Kenny Devorak
Kenny DevorakFlag for United States of America

asked on

creating captcha with a form that onSubmit="return submitForm(this)"

Been trying to get various way of captcha to work with my form.  I use a java script for the form validation.  If everything checks out process the onSubmit="return submitForm(this)".  I'm having a really hard time getting anything to work properly.  If anyone has any examples on how to do this I would greatly appreciate it.


Avatar of hielo
hielo
Flag of Wallis and Futuna image

I suggested a javascript implementation here:
https://www.experts-exchange.com/questions/23458208/setting-up-captcha.html

Did it not work for you? What problems are you getting? Post your HTML code ( not your cf code ).
Avatar of Kenny Devorak

ASKER

Here is my code below


<!--- If form.email isDefined we need to process the form --->
<cfscript>
	if(isDefined("form.email")) {
		member = createObject("component","#Application.cfcRoot#.member");
		security = createObject("component","#Application.cfcRoot#.security");
		if(member.isDuplicate(Application.dsn,form.username,form.email)) {
			variables.message="Either the username or email you entered already exist in the system ... Please Try Again.";
		} else {
			variables.memberID = Member.add(Application.dsn,form.email,form.firstName,form.lastName,form.businessName,form.streetAddress,form.streetAddress1,form.city,form.state,form.phone,form.postalCode);
			variables.securityID = security.addMember(Application.dsn,form.username,form.password,variables.memberid);
			security.joinRole(Application.dsn,"member",variables.securityid);
		}
	}
</cfscript>
<cfif isDefined("variables.memberID")>
  <cflocation url="index.cfm?newMember=1" addtoken="no">
</cfif>
<!--- Invoke the state component to get the states in a query called state. --->
<cfinvoke component="#Application.cfcRoot#.state" method="get" returnvariable="state">
<cfinvokeargument name="dsn" value="#Application.dsn#">
</cfinvoke>
<!--- Invoke the country component to return the query country. --->
<cfinvoke component="#Application.cfcRoot#.country" method="get" returnvariable="country">
<cfinvokeargument name="dsn" value="#Application.dsn#">
</cfinvoke>
<!--- Begin the layout of the membership form ... First import the javascript form library --->
<cfsetting enablecfoutputonly="no">
<script language='JavaScript' src='../_js/js_form.js'></script>
<script>
	// theForm is passed in as an object onsubmit of the form.
	// first call the appropriate functions from the library.
	// The if statement is mandatory.  The variables get defined in the library.
 
	function submitForm(theForm) {
		// validate firstName
		formRequired(theForm.firstName,'You need to enter a First Name.');
		formIsAlphaNumeric(theForm.firstName,'Please enter a valid First Name');
		
		//validate lastName
		formRequired(theForm.lastName,'You need to enter a Last Name.');
		formIsAlphaNumeric(theForm.lastName,'Please enter a valid Last Name');
		
		//validate userName
		formRequired(theForm.userName,'You need to enter a Username.');
		formIsAlphaNumeric(theForm.userName,'Please enter a valid Username');
		
		// validate password and vpassword
		formRequired(theForm.password,'You need to enter a Password.');
		formIsAlphaNumeric(theForm.password,'Please enter a valid Password.');
		formRequired(theForm.vPassword,'You need to verify your Password.');
		formIsAlphaNumeric(theForm.vPassword,'Please enter a valid verification Password.');
		if(formSubmit) {
			formIsSame(theForm.vPassword,theForm.password,'Your password and verifictation password do not match.');
		};
 
		// validate email
		formRequired(theForm.email,'You need to enter an Email Address.');
		if(formSubmit) {
			formIsEmail(theForm.email,'Please enter a valid Email Address.');
		}
				
		if(formSubmit) {
			return true;
		} else {
			formAlert();
			return false;
		}
	}
</script>
<body>
<table cellspacing="0" cellpadding="0" border="0" >
  <tr>
    <td width="1" height="287" bgcolor="E0E0D6"></td>
    <td width="556" height="287" class="column_left1"><cfif isDefined("variables.message")>
        <h3><cfoutput>#variables.message#</cfoutput></h3>
        <cfelse>
        <h3>Become a member</h3>
      </cfif>
      <form action="<cfoutput></cfoutput>" method="post" name="newMember" onSubmit="return submitForm(this)">
        <table width="567" border="0" align="center" cellpadding="0" cellspacing="3" id="formContainer">
          <tr>
            <td width="84" nowrap><div align="right">First Name</div></td>
            <td width="183"><input name="firstName"<cfif isDefined("form.firstName")> value="<cfoutput>#form.firstName#</cfoutput>"</cfif> type="text" tabindex="1" title="First Name" size="25" maxlength="50"></td>
            <td width="100" nowrap><div align="right">Last Name</div></td>
            <td width="185"><input name="lastName" type="text" tabindex="2" title="Last Name" size="25" maxlength="50"></td>
          </tr>
          <tr>
            <td height="18" nowrap><div align="right">Username</div></td>
            <td><input name="userName" type="text" tabindex="3" title="Username" size="25" maxlength="50"></td>
            <td nowrap><div align="right">Email</div></td>
            <td><input name="email" type="text" tabindex="4" title="Email" size="25" maxlength="50"></td>
          </tr>
          <tr>
            <td nowrap><div align="right">Password</div></td>
            <td><input name="password" type="password" tabindex="5" title="Password" size="25" maxlength="15"></td>
            <td nowrap><div align="right">Verify Password</div></td>
            <td><input name="vPassword" type="password" tabindex="6" title="Verify Password" size="25" maxlength="15"></td>
          </tr>
          <tr>
            <td nowrap><div align="right">Business Name</div></td>
            <td colspan="3"><input name="businessName" type="text" id="businessName" tabindex="7" title="Business Name" size="73" maxlength="100" /></td>
          </tr>
          <tr>
            <td nowrap><div align="right">Business Address</div></td>
            <td colspan="3"><input name="streetAddress" type="text" tabindex="8" title="Street Address" size="73" maxlength="100"></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td colspan="3"><input name="streetAddress1" type="text" tabindex="9" title="Street Address" size="73" maxlength="100"></td>
          </tr>
          <tr>
            <td height="24" nowrap><div align="right">City</div></td>
            <td><input name="city" type="text" tabindex="10" title="City" size="25" maxlength="50"></td>
            <td nowrap><div align="right">State/Province </div></td>
            <td><SELECT NAME="state" size="1" id="state" style="width:150;" tabindex="11" title="State/Province">
                <OPTION VALUE="0" selected> Select State/Province </OPTION>
                <cfoutput query="state">
                  <OPTION VALUE="#state.ID#"> #state.name# </OPTION>
                  #chr(10)#</cfoutput>
              </SELECT>
            </td>
          </tr>
          <tr>
            <td nowrap><div align="right">Telephone: </div></td>
            <td><label>
              <input name="phone" type="text" id="phone" size="25" tabindex="12"/>
              </label></td>
            <td nowrap class="small"><div align="right">Postal Code</div></td>
            <td class="small"><input name="postalCode" type="text" tabindex="13" title="Postal Code" size="25" maxlength="50"></td>
          </tr>
          <tr>
            <td colspan="4"><div align="center">
                <input name="Submit" type="submit" value="Join">
                By clicking this button you agree to our<a href="../../terms_of_use.cfm"> terms of service</a></div></td>
          </tr>
        </table>
      </form></td>
    <td width="1" height="287" bgcolor="E0E0D6"></td>
  </tr>
</table>
</td>
</tr>
</table>

Open in new window

what's in "../_js/js_form.js"

again, post ONLY the code that the browser receives. Open your file through
Firefox: View > Page Source
IE6: View > Source

copy that code and paste it here along with the contents of "../_js/js_form.js"
Here is the code you want

 
 
<script language='JavaScript' src='../_js/js_form.js'></script>
<script>
	// theForm is passed in as an object onsubmit of the form.
	// first call the appropriate functions from the library.
	// The if statement is mandatory.  The variables get defined in the library.
 
	function submitForm(theForm) {
		// validate firstName
		formRequired(theForm.firstName,'You need to enter a First Name.');
		formIsAlphaNumeric(theForm.firstName,'Please enter a valid First Name');
		
		//validate lastName
		formRequired(theForm.lastName,'You need to enter a Last Name.');
		formIsAlphaNumeric(theForm.lastName,'Please enter a valid Last Name');
		
		//validate userName
		formRequired(theForm.userName,'You need to enter a Username.');
		formIsAlphaNumeric(theForm.userName,'Please enter a valid Username');
		
		// validate password and vpassword
		formRequired(theForm.password,'You need to enter a Password.');
		formIsAlphaNumeric(theForm.password,'Please enter a valid Password.');
		formRequired(theForm.vPassword,'You need to verify your Password.');
		formIsAlphaNumeric(theForm.vPassword,'Please enter a valid verification Password.');
		if(formSubmit) {
			formIsSame(theForm.vPassword,theForm.password,'Your password and verifictation password do not match.');
		};
 
		// validate email
		formRequired(theForm.email,'You need to enter an Email Address.');
		if(formSubmit) {
			formIsEmail(theForm.email,'Please enter a valid Email Address.');
		}
				
		if(formSubmit) {
			return true;
		} else {
			formAlert();
			return false;
		}
	}
</script>
<body>
<table cellspacing="0" cellpadding="0" border="0" >
  <tr>
    <td width="1" height="287" bgcolor="E0E0D6"></td>
    <td width="556" height="287" class="column_left1">
        <h3>Become a member</h3>
      
      <form action="" method="post" name="newMember" onSubmit="return submitForm(this)">
        <table width="567" border="0" align="center" cellpadding="0" cellspacing="3" id="formContainer">
          <tr>
            <td width="84" nowrap><div align="right">First Name</div></td>
            <td width="183"><input name="firstName" type="text" tabindex="1" title="First Name" size="25" maxlength="50"></td>
            <td width="100" nowrap><div align="right">Last Name</div></td>
            <td width="185"><input name="lastName" type="text" tabindex="2" title="Last Name" size="25" maxlength="50"></td>
          </tr>
          <tr>
            <td height="18" nowrap><div align="right">Username</div></td>
            <td><input name="userName" type="text" tabindex="3" title="Username" size="25" maxlength="50"></td>
            <td nowrap><div align="right">Email</div></td>
            <td><input name="email" type="text" tabindex="4" title="Email" size="25" maxlength="50"></td>
          </tr>
          <tr>
            <td nowrap><div align="right">Password</div></td>
            <td><input name="password" type="password" tabindex="5" title="Password" size="25" maxlength="15"></td>
            <td nowrap><div align="right">Verify Password</div></td>
            <td><input name="vPassword" type="password" tabindex="6" title="Verify Password" size="25" maxlength="15"></td>
          </tr>
          <tr>
            <td nowrap><div align="right">Business Name</div></td>
            <td colspan="3"><input name="businessName" type="text" id="businessName" tabindex="7" title="Business Name" size="73" maxlength="100" /></td>
          </tr>
          <tr>
            <td nowrap><div align="right">Business Address</div></td>
            <td colspan="3"><input name="streetAddress" type="text" tabindex="8" title="Street Address" size="73" maxlength="100"></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td colspan="3"><input name="streetAddress1" type="text" tabindex="9" title="Street Address" size="73" maxlength="100"></td>
          </tr>
          <tr>
            <td height="24" nowrap><div align="right">City</div></td>
            <td><input name="city" type="text" tabindex="10" title="City" size="25" maxlength="50"></td>
            <td nowrap><div align="right">State/Province </div></td>
            <td><SELECT NAME="state" size="1" id="state" style="width:150;" tabindex="11" title="State/Province">
                <OPTION VALUE="0" selected> Select State/Province </OPTION>
                
                  <OPTION VALUE="OH"> Ohio </OPTION>
                  
 
              </SELECT>
            </td>
          </tr>
          <tr>
            <td nowrap><div align="right">Telephone: </div></td>
            <td><label>
              <input name="phone" type="text" id="phone" size="25" tabindex="12"/>
              </label></td>
            <td nowrap class="small"><div align="right">Postal Code</div></td>
            <td class="small"><input name="postalCode" type="text" tabindex="13" title="Postal Code" size="25" maxlength="50"></td>
          </tr>
          <tr>
            <td colspan="4"><div align="center">
                <input name="Submit" type="submit" value="Join">
                By clicking this button you agree to our<a href="../../terms_of_use.cfm"> terms of service</a></div></td>
          </tr>
        </table>
      </form></td>
    <td width="1" height="287" bgcolor="E0E0D6"></td>
  </tr>
</table>
</td>
</tr>
</table>
 
 
 
 
This is the js_form.js
 
 
// Declare Global Variables
 
	var formAlertMessage='There were Errors!';
	var formSubmit=1;
 
/*
	throwError gets called each time there is an error in the
	validation routines.
*/
function throwError (theField,theMessage) {
	formAlertMessage=formAlertMessage + "\n - " + theMessage;
	formSubmit=0;
	switchStyle(theField);
}
function switchStyle (theField) {
	theSwitch=new Function("this.style.backgroundColor='FFFFFF';this.style.color='000000';if(this.type=='text') this.select();")
	theField.style.backgroundColor='FF0000';
	theField.style.color='White';
	theField.onfocus=theSwitch;
}
 
/*
	formAlert displays the alert message and clears necessary variables to start
	the validation over.
*/
 
function formAlert() {
	alert(formAlertMessage);
	formAlertMessage='There were Errors!';
	formSubmit=1;
}
 
 
/*
	formRequired makes sure a field has been completed by the user.   In order
	for this function to work with select boxes the empty value must be set to 0
	in the form.
*/
 
function formRequired(theField,theMessage) {
	theField.value = theField.value.replace(/\s+$|^\s*/gi, "");
	if(theField.value == '' || theField.value == '-1' || theField.value == '0') {
		throwError(theField,theMessage);
	}
}
 
// form field must be composed only of numbers and letters.
function formIsAlphaNumeric(theField,theMessage) {
	theField.value = theField.value.replace(/\s+$|^\s*/gi, "");
	isAlphaNum = new RegExp ("[^0-9a-zA-Z \(\)\-\.\/]");
	if (isAlphaNum.test(theField.value)) {
		throwError(theField,theMessage);
	}
}
 
// form field must be composed only of numbers and letters.
function formIsSame(field1,field2,theMessage) {
 
	if(field1.value != field2.value) {
		throwError(field2,theMessage);
		switchStyle(field1);
	}
}
 
function formIsEmail (theField,theMessage) {
	var email = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
 	if(!email.test(theField.value)) {
		throwError(theField,theMessage);
	}
 }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Almost works.  Only thing is it never excepts the captcha text I enter into it.  
Sorry about that. This line:
if( theForm.userCaptcha.value !== theForm.hiddenCaptcha )

should be:
if( theForm.userCaptcha.value !== theForm.hiddenCaptcha.value )
Now it only throws an error to the user if they don't enter anything in the captcha text box.  If its wrong the program clears the entire form with no error.  If its correct it does the same thing.
>>If its wrong the program clears the entire form with no error.
Not sure why you are seeing that. The code below worked for me with the previously suggested change:
<script language='JavaScript'>
 window.onload=init;
 
 function init()
 {
 	var val = code()
 	document.getElementById('hiddenCaptcha').value=val;
 	document.getElementById('visibleCaptcha').innerHTML=val;
 }
 function Random(X) {
    return Math.floor(X * (Math.random() % 1));
}
 function code() {
    var j, S = ""; 
    for (j = 0; j < 3; j++) {
        S += String.fromCharCode(65 + Random(26));
        S += String.fromCharCode(97 + Random(26));
    }
    return S;
}
 
 
// Declare Global Variables
 
	var formAlertMessage='There were Errors!';
	var formSubmit=1;
 
/*
	throwError gets called each time there is an error in the
	validation routines.
*/
function throwError (theField,theMessage) {
	formAlertMessage=formAlertMessage + "\n - " + theMessage;
	formSubmit=0;
	switchStyle(theField);
}
function switchStyle (theField) {
	theSwitch=new Function("this.style.backgroundColor='FFFFFF';this.style.color='000000';if(this.type=='text') this.select();")
	theField.style.backgroundColor='FF0000';
	theField.style.color='White';
	theField.onfocus=theSwitch;
}
 
/*
	formAlert displays the alert message and clears necessary variables to start
	the validation over.
*/
 
function formAlert() {
	alert(formAlertMessage);
	formAlertMessage='There were Errors!';
	formSubmit=1;
}
 
 
/*
	formRequired makes sure a field has been completed by the user.   In order
	for this function to work with select boxes the empty value must be set to 0
	in the form.
*/
 
function formRequired(theField,theMessage) {
	theField.value = theField.value.replace(/\s+$|^\s*/gi, "");
	if(theField.value == '' || theField.value == '-1' || theField.value == '0') {
		throwError(theField,theMessage);
	}
}
 
// form field must be composed only of numbers and letters.
function formIsAlphaNumeric(theField,theMessage) {
	theField.value = theField.value.replace(/\s+$|^\s*/gi, "");
	isAlphaNum = new RegExp ("[^0-9a-zA-Z \(\)\-\.\/]");
	if (isAlphaNum.test(theField.value)) {
		throwError(theField,theMessage);
	}
}
 
// form field must be composed only of numbers and letters.
function formIsSame(field1,field2,theMessage) {
 
	if(field1.value != field2.value) {
		throwError(field2,theMessage);
		switchStyle(field1);
	}
}
 
function formIsEmail (theField,theMessage) {
	var email = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
 	if(!email.test(theField.value)) {
		throwError(theField,theMessage);
	}
 }
</script>
<script>
	// theForm is passed in as an object onsubmit of the form.
	// first call the appropriate functions from the library.
	// The if statement is mandatory.  The variables get defined in the library.
 
	function submitForm(theForm) {
		// validate firstName
		formRequired(theForm.firstName,'You need to enter a First Name.');
		formIsAlphaNumeric(theForm.firstName,'Please enter a valid First Name');
		
		//validate lastName
		formRequired(theForm.lastName,'You need to enter a Last Name.');
		formIsAlphaNumeric(theForm.lastName,'Please enter a valid Last Name');
		
		//validate userName
		formRequired(theForm.userName,'You need to enter a Username.');
		formIsAlphaNumeric(theForm.userName,'Please enter a valid Username');
		
		// validate password and vpassword
		formRequired(theForm.password,'You need to enter a Password.');
		formIsAlphaNumeric(theForm.password,'Please enter a valid Password.');
		formRequired(theForm.vPassword,'You need to verify your Password.');
		formIsAlphaNumeric(theForm.vPassword,'Please enter a valid verification Password.');
		formRequired(theForm.userCaptcha,'Please enter sign up code.');
 
		if(formSubmit) {
			formIsSame(theForm.vPassword,theForm.password,'Your password and verifictation password do not match.');
		};
 
		// validate email
		formRequired(theForm.email,'You need to enter an Email Address.');
		if(formSubmit) {
			formIsEmail(theForm.email,'Please enter a valid Email Address.');
		}
 
		if( formSubmit)
		{
			if( theForm.userCaptcha.value !== theForm.hiddenCaptcha.value )
			{
				formSubmit=false;
				throwError(theForm.userCaptcha,'Signup Code is incorrect');
				//generate a new captcha code
				init();
			}
		}
 
		if(formSubmit) {
			return true;
		} else {
			formAlert();
			return false;
		}
	}
</script>
<body>
<table cellspacing="0" cellpadding="0" border="0" >
  <tr>
    <td width="1" height="287" bgcolor="E0E0D6"></td>
    <td width="556" height="287" class="column_left1">
        <h3>Become a member</h3>
      
      <form action="" method="post" name="newMember" onSubmit="return submitForm(this)">
        <table width="567" border="0" align="center" cellpadding="0" cellspacing="3" id="formContainer">
          <tr>
            <td width="84" nowrap><div align="right">First Name</div></td>
            <td width="183"><input name="firstName" type="text" tabindex="1" title="First Name" size="25" maxlength="50"></td>
            <td width="100" nowrap><div align="right">Last Name</div></td>
            <td width="185"><input name="lastName" type="text" tabindex="2" title="Last Name" size="25" maxlength="50"></td>
          </tr>
          <tr>
            <td height="18" nowrap><div align="right">Username</div></td>
            <td><input name="userName" type="text" tabindex="3" title="Username" size="25" maxlength="50"></td>
            <td nowrap><div align="right">Email</div></td>
            <td><input name="email" type="text" tabindex="4" title="Email" size="25" maxlength="50"></td>
          </tr>
          <tr>
            <td nowrap><div align="right">Password</div></td>
            <td><input name="password" type="password" tabindex="5" title="Password" size="25" maxlength="15"></td>
            <td nowrap><div align="right">Verify Password</div></td>
            <td><input name="vPassword" type="password" tabindex="6" title="Verify Password" size="25" maxlength="15"></td>
          </tr>
          <tr>
            <td nowrap><div align="right">Business Name</div></td>
            <td colspan="3"><input name="businessName" type="text" id="businessName" tabindex="7" title="Business Name" size="73" maxlength="100" /></td>
          </tr>
          <tr>
            <td nowrap><div align="right">Business Address</div></td>
            <td colspan="3"><input name="streetAddress" type="text" tabindex="8" title="Street Address" size="73" maxlength="100"></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td colspan="3"><input name="streetAddress1" type="text" tabindex="9" title="Street Address" size="73" maxlength="100"></td>
          </tr>
          <tr>
            <td height="24" nowrap><div align="right">City</div></td>
            <td><input name="city" type="text" tabindex="10" title="City" size="25" maxlength="50"></td>
            <td nowrap><div align="right">State/Province </div></td>
            <td><SELECT NAME="state" size="1" id="state" style="width:150;" tabindex="11" title="State/Province">
                <OPTION VALUE="0" selected> Select State/Province </OPTION>
                
                  <OPTION VALUE="OH"> Ohio </OPTION>
                  
 
              </SELECT>
            </td>
          </tr>
          <tr>
            <td nowrap><div align="right">Telephone: </div></td>
            <td><label>
              <input name="phone" type="text" id="phone" size="25" tabindex="12"/>
              </label></td>
            <td nowrap class="small"><div align="right">Postal Code</div></td>
            <td class="small"><input name="postalCode" type="text" tabindex="13" title="Postal Code" size="25" maxlength="50"></td>
          </tr>
		<tr>
			<td colspan="2">Signup Code: <span style="font-weight:bold;color:navy;background-color:#ededed;" id="visibleCaptcha"></span></td>
		</tr>
		<tr>
			<td colspan="2">Enter Signup Code: <input type="text" name="userCaptcha" id="userCaptcha" value=""/></td>
		</tr>
          <tr>
            <td colspan="4"><div align="center"><input type="hidden" name="hiddenCaptcha" id="hiddenCaptcha" value=""/>
                <input name="Submit" type="submit" value="Join">
                By clicking this button you agree to our<a href="../../terms_of_use.cfm"> terms of service</a></div></td>
          </tr>
        </table>
      </form></td>
    <td width="1" height="287" bgcolor="E0E0D6"></td>
  </tr>
</table>
</td>
</tr>
</table>
 
 
  

Open in new window

If the Captcha is correct and I want to run a query to insert the form into a database where would I insert the query
>>where would I insert the query
NOT on the browser code. What I gave you is just the browser code. I'm not a cf developer so I can't help you with that. Kindly open a new problem (under cf zone) since that is a separate issue.