...

View Full Version : PHP validating form first, even with Javascript validation?



karlosio
10-13-2009, 01:25 AM
Hi I have a sign up page where I have JavaScript validation and server-side validation (PHP). When I click on the submit button without entering anything, I get the PHP validation error message appearing before I get the JavaScript validation error. If I click on the submit button again, I then get the JavaScript error. Surely the JavaScript error should validate first? Could someone please let me know where I'm going wrong with this. :S

I have created a simple stripped down page (no php checks for any nasty stuff) so I can test it as I have recently created a larger form with more thorough checks but I have been getting the same problem.

This is my simple test page:



<script type="text/javascript">
function valid(form)
{
var err = document.getElementById('err');
for(var i = 0; i < form.elements.length; i++)
{
var el = form.elements[i];
if(el.type == 'text')
{
if(el.value == '')
{
err.innerHTML = 'No info entered';
return false;
}
}
}
return true;
}
</script>
</head>

<body>
<?php
$error = 0;
$msg = '';
if(isset($_POST['submit']))
{
$field1 = $_POST['field1'];
$field2 = $_POST['field2'];

if(empty($field1) || empty($field2))
{
$error = 1;
$msg = 'Enter something into the field';
}
else {
$error = 1;
$msg = 'Everything is ok';
}
}
if(!isset($_POST['submit']) || $error == 1)
{
?>
<div id="err">
<?=$msg;?>
</div>
<form id="regform" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" onsubmit="return valid(this)">
<label for="field1">Field 1:</label>
<input type="text" name="field1" id="field1" size="30" value="<?php echo (isset($_POST['field1'])) ? $_POST['field1'] : '';?>" /><br />
<label for="field2">Field 2</label>
<input type="text" name="field2" id="field2" size="30" value="<?php echo (isset($_POST['field2'])) ? $_POST['field2'] : '';?>" /><br />
<input type="submit" name="submit" value="Test" />
</form>
<?php
}
?>

Fou-Lu
10-13-2009, 01:44 AM
Works for me, are you certain you're javascript is enabled?
The PHP validation does not however work by default. This is because my configurations do not accept short tags, so I had to change the <?=$msg;?> to <?php echo $msg;?>.

karlosio
10-13-2009, 01:59 AM
Doh, something so simple. I don't even remember disabling it but I must have :o . Jeez....

Thanks



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum