Simple required field validation php

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tora0515
Forum Newbie
Posts: 1
Joined: Wed Dec 29, 2010 12:29 pm

Simple required field validation php

Post 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'] . '!';
}
?>
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Simple required field validation php

Post 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.
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply