Jump to content


Javascript Form Validation


5 replies to this topic

#1 Chris.

    Young Padawan

  • Members
  • Pip
  • 129 posts
  • Gender:Male

Posted 04 May 2007 - 01:28 PM

i have a javascript form validation script, and I need some help. First of all, here is my code.

<script type="text/javascript">
<!--
function validate_form()
{

	if(document.comment.title.value == "" || document.comment.author.value == "" || document.comment.comment.value == "" || document.comment.captcha.value == "")
	{
		alert ( "ERROR\n\nPossible Error(s)\n - You did not enter a title\n - You did not enter your username as the author\n - You did not enter a comment\n - The security verification code you entered does not match that of the image\n\n Please double check the form and make sure that you entered values for each and every field.  Also double check that the security verification code you typed matches that of the image." );
		return false;
	}
	else
	{
		document.comment.submit();
	}
}
//-->
</script>

Now, I want to make it check the document.comment.captha.value again, but make sure it is set to a certain value. That value is a PHP Captcha Image, which would be $_SESSION['veri'];. I tried many ways to get this to work. I tried

if(document.comment.captcha.value != "<?php echo'$_SESSION[veri]'; ?>") { }

But that didn't work. I also tried using other variations of the quotes but none succeeded to work. Does anyone know how to do this? Thanks.

#2 Archangel

    P2L Jedi

  • Members
  • PipPipPip
  • 988 posts
  • Gender:Male
  • Location:Indiana
  • Interests:Reading (mainly fantasy books), Gaming (Xbox 360, Wii &amp; PS3), Sports, Outdoor Recreation, Watching/Collecting Movies

Posted 04 May 2007 - 02:28 PM

The reason that's not working is b/c the javascript is called once the page is loaded and you can't use that php until the page is reloaded (client side scripting vs. server side scripting). I think I've read ways to get them to interact, but can't remember. Off the top of my head I can think of a round-about way that might work for ya.

When creating the page use a hidden form variable set to <?php echo'$_SESSION[veri]'; ?> or...

<input type="hidden" id="fVeri" value="<?php echo'$_SESSION[veri]'; ?>" />

Now you have something javascript can pull from.

if(document.comment.captcha.value != document.getElementByID('fVeri')){}

or...something like that.

#3 Demonslay

    P2L Jedi

  • Members
  • PipPipPip
  • 970 posts
  • Gender:Male
  • Location:A strange world where water falls out of the sky... for no reason.
  • Interests:Graphic Design, Coding, Splinter Cell, Cats

Posted 04 May 2007 - 03:38 PM

View PostArchangel, on May 4 2007, 02:28 PM, said:

The reason that's not working is b/c the javascript is called once the page is loaded and you can't use that php until the page is reloaded (client side scripting vs. server side scripting). I think I've read ways to get them to interact, but can't remember. Off the top of my head I can think of a round-about way that might work for ya.

When creating the page use a hidden form variable set to <?php echo'$_SESSION[veri]'; ?> or...

<input type="hidden" id="fVeri" value="<?php echo'$_SESSION[veri]'; ?>" />

Now you have something javascript can pull from.

if(document.comment.captcha.value != document.getElementByID('fVeri')){}

or...something like that.

RED FLAG

Bad idea. That completely kills the idea of CAPTCHA.

In building my own CAPTCHA system, I've come to understand how this works.
  • The page is loaded, no $_SESSION values exist
  • The CAPTCHA image is called on the page
  • The CAPTCHA image stores the $_SESSION value to its current string generated on the image
  • The form is sent
  • The session value is then compared to the submitted form, and action is taken
Take a close look at the first step. At the time the page is generated, no session data for the CAPTCHA image is set, and if it is, then it is equal to the very last time the user has seen the image, and thus isn't equal to the current image.

There are ways you could validate this, but to be honest, to me it wouldn't be worth it. If the user doesn't submit a valid security code, simply save the data and throw it back to the user inside the form with the warning that the code wasn't valid.

#4 Chris.

    Young Padawan

  • Members
  • Pip
  • 129 posts
  • Gender:Male

Posted 04 May 2007 - 05:51 PM

Oh, so there is no sure fire way to do this other than through server side scripting (PHP) validation?

#5 Archangel

    P2L Jedi

  • Members
  • PipPipPip
  • 988 posts
  • Gender:Male
  • Location:Indiana
  • Interests:Reading (mainly fantasy books), Gaming (Xbox 360, Wii &amp; PS3), Sports, Outdoor Recreation, Watching/Collecting Movies

Posted 04 May 2007 - 08:28 PM

View PostDemonslay, on May 4 2007, 04:38 PM, said:

View PostArchangel, on May 4 2007, 02:28 PM, said:

The reason that's not working is b/c the javascript is called once the page is loaded and you can't use that php until the page is reloaded (client side scripting vs. server side scripting). I think I've read ways to get them to interact, but can't remember. Off the top of my head I can think of a round-about way that might work for ya.

When creating the page use a hidden form variable set to <?php echo'$_SESSION[veri]'; ?> or...

<input type="hidden" id="fVeri" value="<?php echo'$_SESSION[veri]'; ?>" />

Now you have something javascript can pull from.

if(document.comment.captcha.value != document.getElementByID('fVeri')){}

or...something like that.

RED FLAG

Bad idea. That completely kills the idea of CAPTCHA.

In building my own CAPTCHA system, I've come to understand how this works.
  • The page is loaded, no $_SESSION values exist
  • The CAPTCHA image is called on the page
  • The CAPTCHA image stores the $_SESSION value to its current string generated on the image
  • The form is sent
  • The session value is then compared to the submitted form, and action is taken
Take a close look at the first step. At the time the page is generated, no session data for the CAPTCHA image is set, and if it is, then it is equal to the very last time the user has seen the image, and thus isn't equal to the current image.

There are ways you could validate this, but to be honest, to me it wouldn't be worth it. If the user doesn't submit a valid security code, simply save the data and throw it back to the user inside the form with the warning that the code wasn't valid.

My mistake :)

#6 Demonslay

    P2L Jedi

  • Members
  • PipPipPip
  • 970 posts
  • Gender:Male
  • Location:A strange world where water falls out of the sky... for no reason.
  • Interests:Graphic Design, Coding, Splinter Cell, Cats

Posted 05 May 2007 - 11:45 AM

It would be safer anyways, as you should have it validating on the server side no matter what.
Always remember. Server-side validation (PHP) is mandatory, as its sure to work no matter what, and is your main script; using client-side validation (JavaScript) is only a convenience for the user.

Now that I remember, I do use AJAX myself to validate the code, but it is when it is actually sent to the server, so it isn't fully client-side. It simply submits the entire form to my script with AJAX, then the script validates it against the session data, and if it doesn't match, it replies with a special flag, that tells my AJAX handler to run a reset function, which alerts the user that the security code was incorrect, saves the form data onto a temporary session value, and then completely refreshes the page. My page then has the form able to grab that session data if it exists, and puts it back into the form.

Here's a simple example. (Uses the Prototype Library)

JavaScript
/* Sendmail Object */
var Sendmail = {

	// AJAX Send Email
	Send: function(){
		if(!checkform('contact')) return false;
		var opt = {
			method:'post', 
			postBody: Form.serialize('contact_form'),
			onSuccess: function(t) { Sendmail.HandleSend(t); },
			onLoading: function() { $('submit').value = 'Sending...'; $('submit').disabled = true; $('response').innerHTML = '<img src="/images/icons/loading.gif" alt="Loading... Please Wait" />'; }
			}
		new Ajax.Request('/ajax/sendmail.php', opt);
	},

	// Handle Send Email
	HandleSend: function(t){
		data = t.responseText.split('|');
		if(data[0] == 1) $('submit').value = 'Message Sent!';
		else if(data[0] == -1){
			alert(data[1]);
			reset_contact();
		}
		else{
			$('submit').value = 'Submit';
			$('submit').disabled = false;
		}
		$('form_response').innerHTML = data[1];
	}
}

Contact Page
<?php
// Grab Previous Form Data
$form = isset($_SESSION['contact_form']) ? unserialize($_SESSION['contact_form']) : array();
function getdata($data){
	global $form;
	echo htmlspecialchars($form[$data]);
}
?>
<div class="box">
	<h2><span style="font-size:10px;">&divide;</span> Contact Us</h2>
	<p>Please use this form to contact us concerning anything.</p>
</div>
<br /><br />
<form id="contact_form" name="contact_form" action="/contact.php" method="post" onsubmit="return false;">
	<h2>Contact Form</h2>
	<table cellpadding="5" cellspacing="0" style="text-align:center;margin:0 auto;width:100%;">
		<tr>
			<td><strong>Subject:</strong></td>
			<td><input id="contact_subject" type="text" name="contact_subject" maxlength="255" style="width:280px;" value="<?php getdata('subject'); ?>" /></td>
		</tr>
		<tr>
			<td><strong>Name:</strong></td>
			<td><input id="contact_name" type="text" name="contact_name" maxlength="15" style="width:280px;" value="<?php getdata('name'); ?>" /></td>
		</tr>
		<tr>
			<td><strong>Email Address:</strong></td>
			<td><input id="contact_email" type="text" name="contact_email" maxlength="255" style="width:280px;" value="<?php getdata('email'); ?>" /></td>
		</tr>
		<tr>
			<td><strong>Message:</strong></td>
			<td><textarea id="message" name="message" style="width:280px;" rows="10" cols="10"><?php getdata('message'); ?></textarea></td>
		</tr>
		<tr>
			<td>
				<strong>Security Code:</strong><br />
				<img src="/lib/security_image.php" alt="Security Image" title="Please enter this code into the input field to the right." /><br /><a href="java script:reset_contact();">Cannot see image?</a>
			</td>
			<td><input id="security_image" type="text" name="security_image" maxlength="5" style="width:200px;" /></td>
		</tr>
		<tr>
			<td align="center" colspan="2"><input type="submit" id="submit" name="submit" onclick="Sendmail.Send();" value="Submit" /> &nbsp;&nbsp;<input type="reset" onclick="return reset_form('contact_form')" value="Reset" /></td>
		</tr>
	</table>
</form>
<div id="form_response">&nbsp;</div>

AJAX Handling File
<?php
// Cleaning Functions

// Strip HTML Function
function strip_html($data){
	$search = array('@<script[^>]*?>.*?</script>@si', // Strip Javascript
					'@<style[^>]*?>.*?</style>@siU',  // Strip Style Tags
					'@<[\/\!]*?[^<>]*?>@si',		  // Strip HTML tags
					'@<![\s\S]*?--[ \t\n\r]*>@'		  // Strip Multi-line Comments (CDATA)
	);
	return preg_replace($search, '', $data);
}

// Clean User Data Function
function cleandata($data){
	return trim(htmlspecialchars(strip_html($data)));
}

// Send Email

if(!$_POST['submit'])
	$message_error['Invalid Data'] = 'The information you have submitted does not appear to have been correctly submitted by our form. If you recieve this error after correctly filling out our form, please contact us through another method.';

if($_SERVER['REQUEST_METHOD'] != 'POST')
	$message_error['Unauthorized Access'] = 'This page has been accessed through an unauthorized method. Please go back and submit through the form correctly.';

// Retrieve Form Variables
$subject = SITE_NAME.': '.cleandata($_POST['contact_subject']);
$name = cleandata($_POST['contact_name']);
$email = cleandata($_POST['contact_email']);
$message = cleandata($_POST['message']);
$headers = 'From: '.SITE_NAME.' <'.EMAIL_FEEDBACK.">\nReply-To: {$name} <{$email}>\n";

if(strtolower($_POST['security_image']) != strtolower($_SESSION['gen_key'])){
	$_SESSION['contact_form'] = serialize('subject' => $subject, 'name' => $name, 'email' => $email, 'message' =>$message);
	if($ajax)
		echo "-1|Invalid Security Code\n\nSorry, but the code you entered does not match the image. Please try again."
	else
		echo '<div class="box"><h2><span style="font-size:10px;">&divide;</span> Error!</h2><p class="error"><strong>Message Error:</strong> <span class="red">Invalid Security Code</span><br /><span class="indent">Sorry, but the code you entered does not match the image. Please try again.</span></p></div>';
	return;
}
else
	unset($_SESSION['contact_form'], $_COOKIE['contact_form'], $_SESSION['gen_key']);

// Ensure No Blank Fields
if(is_type('empty', $subject, $name, $email, $message))
	$message_error['Missing Information'] = 'It appears you did not fill the entire form out. Please make sure all required fields are filled out correctly and try again.';

// Regex Validate Email
if(!preg_match('#([._a-z0-9-]+[._a-z0-9-]*)@(([a-z0-9-]+\.)*([a-z0-9-]+)(\.[a-z]{2,3})?)#i', $email))
	$message_error['Invalid Email'] = 'The email submitted does not appear to be a correct email. Please check your email address and try again.';

// Exploits Validate Email
if(preg_match('#(content-type|bcc:|cc:|document.cookie|onclick|onload)#i', $email))
	$message_error['Exploit Found'] = 'The email submitted appears to contain exploits. Please check your email address and try again.';

// Exploits Validate Message
if(preg_match('#(content-type|bcc:|cc:|document.cookie|onclick|onload)#i', $message))
	$message_error['Exploit Found'] = 'The message submitted appears to contain exploits. Please check your message and try again.';

// Name Length Validate
if(strlen($name) > 15)
	$message_error['Name Length Exceeds Limit'] = 'The name submitted is longer than 15 characters. Please check your name and try again.';

// Name Character Validate
if(!preg_match('#([A-Za-z\' -]*)#i', $name))
	$message_error['Invalid Name'] = 'The name submitted contains special characters. Please remove any special characters and try again.';

$message = 'This e-mail has been sent by '.SITE_NAME.' &lt;'.SITE_URL."&gt;\n\nMessage Details:\nIP Address: {$_SERVER['REMOTE_ADDR']}\nBrowser: {$_SERVER['HTTP_USER_AGENT']}\nE-Mail Time:".formatDate(date('Y-m-d H:i:s'))."\n\n\nMessage:\n".$message;
if(empty($message_error)){
	// Send Message
	if(@mail(EMAIL_ADMIN, $subject, $message, $headers))
		// Echo Success
		echo '1|<div class="box"><h2><span style="font-size:10px;">&divide;</span> Thank You!</h2><p>Your message has been recieved.</p></div>';
	else
		// Echo Error
		$message_error['Error Sending Mail'] = 'An unknown error has occured while trying to send your email. This may be a problem on our end. Please try again, or contact us via messanger about this problem.';
}

if(!empty($message_error)){
	$return = '<div class="box"><h2><span style="font-size:10px;">&divide;</span> Error!</h2>';
	foreach($message_error as $k => $v)	$return .= "<p class=\"error\"><strong>Message Error:</strong> <span class=\"red\">{$k}</span><br /><span class=\"indent\">{$v}</span></p>\n";
	echo  '0|'.$return.'</div><br />';
}
?>

Has some stuff in there specific to the site I am building, such as the cleandata() function, but that should show you a very secure way of validating your data incase you haven't already implicated such things.

Edited by Demonslay, 05 May 2007 - 11:48 AM.






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users