...

View Full Version : Why Form Validation Isn't Working



Pennimus
02-16-2006, 10:52 PM
I can get through this and post blank comments at will; what's wrong with the validation?



$comment1 = $_POST['comment'];

if (!isset($_POST['comment'])) {
header ("Location: http://www.site.com/error.php");
exit();

} elseif (empty($comment1)) {
header ("Location: http://www.site.com/error.php");
exit();

} else {

$comment2 = nl2br($comment1);
$comment3 = str_replace ('<a ','<a rel="nofollow" ',$comment2);
// then execute rest of formhandler...
}

_Aerospace_Eng_
02-17-2006, 04:57 AM
Try this, check to see if submitted first then check to see if comment is empty.

<?php
if(isset($_POST['submit']) && $_POST['submit'] == 'Submit') //if submitted
{
$comment1 = stripslashes($_POST['comment']);
if(empty($comment1)) //if $comment1 is blank
{
header ("Location: http://www.site.com/error.php");
exit();
}
else
{
$comment2 = nl2br($comment1);
$comment3 = str_replace ('<a ','<a rel="nofollow" ',$comment2);
// then execute rest of formhandler...
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
function isValid(form)
{
if(form.comment.value == '')
{
alert('You must enter a comment');
form.comment.focus();
return false;
}
}
</script>
</head>

<body>
<form action="<?php echo $_SERVER['SCRIPT_NAME']?>" method="post" onsubmit="return isValid(this)">
Comment1 : <br /><textarea name="comment" cols="40" rows="10"></textarea><br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
I added in some JS validation because its a good idea to do both clientside and server side validation.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum