Page 1 of 1

Simple required field validation php

Posted: Wed Dec 29, 2010 12:33 pm
by tora0515
I am not sure where to place the validation script:

if (! strlen($_POST['first_name'])) {
echo 'You must enter your first name.';

As it is now, the echo 'You must.... is being echoed onto the page when it is loaded. You can check it at http://www.studylinkjapan.com/testform.php

The code is below:



<?php if ($_SERVER['REQUEST_METHOD'] == 'GET')
{
?>
<form action="<?php echo $_SERVER['SCRIPT_NAME'] ?>" method="post">
What is your first name?
<input type="text" name="first_name" />
<input type="submit" value="Say Hello" />
</form>
<?php
}
if (! strlen($_POST['first_name'])) {
echo 'You must enter your first name.';
}
else
{
echo 'Hello, ' . $_POST['first_name'] . '!';
}
?>

Re: Simple required field validation php

Posted: Wed Dec 29, 2010 5:17 pm
by social_experiment

Code: Select all

<?php if(isset($_POST['submitButton']))
 {
 // validation here. 
 }
 ?>
By checking whether the button is set, instead of the field name, nothing is displayed when the page is first loaded. Modify your form code:

Code: Select all

<input type="form" name="submitButton" value="Say hello" />
If you want to check whether a name has been entered, simply use isset() on the particular field as well. strlen() is used incorrectly in this context.