How Do I Make Form Fields Compulsory?

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

furiousweebee
Forum Commoner
Posts: 69
Joined: Sun Jul 11, 2004 7:38 am
Location: Brisbane, Australia
Contact:

How Do I Make Form Fields Compulsory?

Post by furiousweebee »

Hey there everyone... my problem is probably fairly simple for anyone with a decent understanding of PHP but I'm pretty much an amateur in that respect.

Anyway, what I'm doing is creating a user database where visitors are able to enter their details which will be stored in a MySQL database.

I have no problem creating the form which submits the information, but I want some fields to be compulsory, and others not. To achieve this, I want the page to refresh (or use DHTML...) to point out to the user that a particular field is not filled in, or is invalid. (eg "You have not filled in blah blah field"). Only after all the fields are filled in should their submission be accepted. Anyway without further adieu, here is the code I have:

Code: Select all

<form enctype="multipart/form-data" action="street_team.php" method="post">
<table width="100%"  border="0" cellspacing="0" cellpadding="2">
  <tr valign="top">
    <td width="34%">First Name:</td>
    <td width="66%"><input class="input" name="first_name" type="text" size="25"></td>
  </tr>
  <tr valign="top">
    <td>Last Name:</td>
    <td><input class="input" name="last_name" type="text" size="25"></td>
  </tr>
  <tr valign="top">
    <td>Birth Year:</td>
    <td><input class="input" name="birth_year" type="text" size="4"></td>
  </tr>
  <tr valign="top">
    <td>Email Address:</td>
    <td><input class="input" name="email" type="text" size="35"></td>
  </tr>
  <tr valign="top">
    <td>Postal Address:</td>
    <td><input class="input" name="address" type="text" size="35"></td>
  </tr>
  <tr valign="top">
    <td>City:</td>
    <td><input class="input" name="city" type="text" size="20"></td>
  </tr>
  <tr valign="top">
    <td>State / Province:</td>
    <td><input class="input" name="state_province" type="text" size="20"></td>
  </tr>
  <tr valign="top">
    <td>Zip / Post Code: </td>
    <td><input class="input" name="zip" type="text" size="8"></td>
  </tr>
  <tr valign="top">
    <td>Country:</td>
    <td><select size="1" name="country" class="input">
      <option selected>Other</option>
      <option>Argentina</option>
      <option>Australia</option>
      <option>Belgium</option>
      <option>Brazil</option>
      <option>Canada</option>
      <option>Chile</option>
      <option>China</option>
      <option>Colombia</option>
      <option>Croatia</option>
      <option>Czech Republic</option>
      <option>Denmark</option>
      <option>Ecuador</option>
      <option>England</option>
      <option>Finland</option>
      <option>France</option>
      <option>Germany</option>
      <option>Great Britain</option>
      <option>Hungary</option>
      <option>Ireland</option>
      <option>Italy</option>
      <option>Japan</option>
      <option>Mexico</option>
      <option>N Ireland</option>
      <option>Netherlands</option>
      <option>New Zealand</option>
      <option>Norway</option>
      <option>Portugal</option>
      <option>Russia</option>
      <option>Scotland</option>
      <option>South Africa</option>
      <option>Spain</option>
      <option>Sweden</option>
      <option>Switzerland</option>
      <option>Uruguay</option>
      <option>USA</option>
      <option>Wales</option>
    </select></td>
  </tr>
  <tr valign="top">
    <td>Continent</td>
    <td><input class="input" name="continent" type="text" size="20"></td>
  </tr>
  <tr valign="top">
    <td>Phone Number:</td>
    <td><input class="input" name="phone" type="text" size="20"></td>
  </tr>
  <tr valign="top">
    <td>Nearest Major City:</td>
    <td><input class="input" name="major_city" type="text" size="20"></td>
  </tr>
  <tr valign="top">
    <td>Favorite Venues/Hangouts:</td>
    <td><textarea rows="5" name="faves" cols="30" class="input"></textarea></td>
  </tr>
  <tr valign="top">
    <td>Comments:</td>
    <td><textarea rows="5" name="comments" cols="30" class="input"></textarea></td>
  </tr>
  <tr valign="top">
    <td colspan="2" align="center"><input type="submit" value="Join The Team!" name="street_team_data">
    </td>
  </tr>
</table>

</form>

Code: Select all

<?PHP

$database_name = "my_database";

$dbh = mysql_connect("localhost","my_username","my_password");

if (!mysql_select_db($database_name)) {
  echo "Unable to select "$database_name" database";
}

$first_name = $_POST['first_name'];
$date=date("Y-m-d");
$last_name = $_POST['last_name'];
$birth_year = $_POST['birth_year'];
$email = $_POST['email'];
$address = $_POST['address'];
$city = $_POST['city'];
$state_province = $_POST['state_province'];
$country = $_POST['country'];
$zip = $_POST['zip'];
$continent = $_POST['continent'];
$phone = $_POST['phone'];
$major_city = $_POST['major_city'];
$faves = $_POST['faves'];
$comments = $_POST['comments'];

if ($_POST['street_team_data']){

// log user ip address and check bans

$banned = false;
$banlist[] = '';

if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
 $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
else
 $ip = $_SERVER["REMOTE_ADDR"];

$octets1 = explode(".", $ip);
foreach ($banlist as $val){
	$octets2 = explode(".", $val);
	if (	($octets1[0] == $octets2[0] || $octets2[0] == "*") && ($octets1[1] == $octets2[1] || $octets2[1] == "*") && 
		($octets1[2] == $octets2[2] || $octets2[2] == "*") && ($octets1[3] == $octets2[3] || $octets2[3] == "*")){
			$banned = true;
			break;
	}
}

$sql = "insert into street_team (date, first_name, last_name, birth_year, email, address, city, state_province, country, zip, continent, phone, major_city, faves, comments, ip) 
values '$date', '$first_name', '$last_name', '$birth_year', '$email', '$address', '$city', '$state_province', '$country', '$zip', '$continent', '$phone', '$major_city', '$faves', '$comments', '$ip')";

if (!$banned)
{
$res = mysql_query($sql,$dbh);
if (!$res) {
	echo mysql_errno().": ".mysql_error ()."";
	return 0;
}
}

  echo"Submission was successful!";
 
}
?>
I would really appreciate any help. Related to this same database, I want users to be able to give themselves a username and password and be automatically assigned a 5 character alphanumerial random membership ID but I'm unsure how to go about it. But for now I just need to get the first part working... I hope this isn't asking too much. :oops:
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

generally, I only run a [php_man]preg_match[/php_man]() over all required fields. For optional fields, I check if they are not [php_man]empty[/php_man](), then run a preg_match for validation.

Side note: it's not advisable to check if the submit button was passed as it won't be passed if someone uses their enter key to submit the form.
furiousweebee
Forum Commoner
Posts: 69
Joined: Sun Jul 11, 2004 7:38 am
Location: Brisbane, Australia
Contact:

Post by furiousweebee »

Sorry to be a pain but could you give me an example of how I'd do this (using my code above)? The fields that aren't required are:

phone
major_city
faves
comments

Thanks for your help thus far!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

<?php

foreach($_POST as $k => $v)
{
  $data = array();
  $valid = array();
  // the following can be used for exclusion and/or inclusion control
  switch($k)
  {
    case 'street_team_data':
      // ignore this value
      break;
    case 'first_name':
      $data[$k] = $v;
      $valid[$k] = !preg_match('#[0-9]#',$v);
      break;
    case 'phone':
      $data[$k] = $v;
      $valid[$k] = ( empty( $v ) ? 1 : preg_match('#^[0-9().-]+$#i',$v) );
      break;
    default:
      $data[$k] = $v;
      $valid[$k] = preg_match
      break;
  }

?>
furiousweebee
Forum Commoner
Posts: 69
Joined: Sun Jul 11, 2004 7:38 am
Location: Brisbane, Australia
Contact:

Post by furiousweebee »

So I'd just leave everything I had above intact, add further fields to your code as required, and add your code below the following line?

Code: Select all

if ($_POST['street_team_data']){
Also, how would I then make the error messages appear at the top of the page (eg "You have not filled in your Last Name") without losing the information they've filled in?

Let me know if I'm being a pest...
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

for the most part, you can leave it intact. I wouldn't use the if($_POST['street_team_data']), because it may not be submitted.

for the error messages, you just need to run through the $valid associative array to find which ones passed and which ones failed.
furiousweebee
Forum Commoner
Posts: 69
Joined: Sun Jul 11, 2004 7:38 am
Location: Brisbane, Australia
Contact:

Post by furiousweebee »

Ok, so I ditch that if($_POST['street_team_data']) line, but I don't know (at all) how to make the error messages appear. I'm not trying to get someone to rewrite the entire thing for me because I want to learn how to do this stuff, but at the moment I'm really struggling to understand it all.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

use another foreach, or, you can check the result of the validation immediately after it's set to echo a new line when it's false..
furiousweebee
Forum Commoner
Posts: 69
Joined: Sun Jul 11, 2004 7:38 am
Location: Brisbane, Australia
Contact:

Post by furiousweebee »

Like this?

Code: Select all

case 'first_name': 
      $data[$k] = $v; 
      $valid[$k] = !preg_match('#[0-9]#',$v);
      if (!$valid('first_name')) { 
          echo "Fill in your first name, hippy!"; 
}
      break;
I am sooooo stupid. :D
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

very similar to that :)

Code: Select all

case 'first_name': 
      $data[$k] = $v; 
      $valid[$k] = !preg_match('#[0-9]#',$v); 
      if (!$valid[$k]) { 
          echo "Fill in your first name, hippy!"; 
      } 
      break;
furiousweebee
Forum Commoner
Posts: 69
Joined: Sun Jul 11, 2004 7:38 am
Location: Brisbane, Australia
Contact:

Post by furiousweebee »

Wow, I can't believe I was actually on the right track lol. I'll have to go away and give all this a try tonight, and no doubt return with 141 more questions relating to the 97 problems I run into. :D
furiousweebee
Forum Commoner
Posts: 69
Joined: Sun Jul 11, 2004 7:38 am
Location: Brisbane, Australia
Contact:

Post by furiousweebee »

One more quick question... I'm storing people's year of birth as a 4 digit number, and the zip code as alphanumerical. I have these fields set up in MySQL as follows:

birth_year - tinyint(4), not null, default = 0
zip - tinyint(10), not null, default = 0

Is this correct or should they be something else because whatever value I enter on the form, it stores the results as "127"?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

tinyint(4) = -128 - 127 possible numbers.. the 4 is how many characters to allow.. tinyint is only a byte is size.. You should probably use int instead.
furiousweebee
Forum Commoner
Posts: 69
Joined: Sun Jul 11, 2004 7:38 am
Location: Brisbane, Australia
Contact:

Post by furiousweebee »

Thanks, that worked a treat. :D
furiousweebee
Forum Commoner
Posts: 69
Joined: Sun Jul 11, 2004 7:38 am
Location: Brisbane, Australia
Contact:

Post by furiousweebee »

Ok, I made all those changes but now when the page loads, it's blank (there's no form on the page). Here's my PHP code now:

Code: Select all

<?php

$database_name = "my_database"; 

$dbh = mysql_connect("localhost","my_username","my_password"); 

if (!mysql_select_db($database_name)) { 
  echo "Unable to select "$database_name" database"; 
} 

$first_name = $_POST['first_name']; 
$date=date("Y-m-d"); 
$last_name = $_POST['last_name']; 
$birth_year = $_POST['birth_year']; 
$email = $_POST['email']; 
$address = $_POST['address']; 
$city = $_POST['city']; 
$state_province = $_POST['state_province']; 
$country = $_POST['country']; 
$zip = $_POST['zip']; 
$continent = $_POST['continent']; 
$phone = $_POST['phone']; 
$major_city = $_POST['major_city']; 
$faves = $_POST['faves']; 
$comments = $_POST['comments']; 

foreach($_POST as $k => $v) 
{ 
  $data = array(); 
  $valid = array(); 
  // the following can be used for exclusion and/or inclusion control 
  switch($k) 
  { 
    case 'street_team_data': 
      // ignore this value 
      break; 
	case 'first_name': 
      $data[$k] = $v; 
      $valid[$k] = !preg_match('#[0-9]#',$v); 
      if (!$valid[$k]) { 
          echo "You must enter your first name"; 
      } 
      break;
	case 'last_name': 
      $data[$k] = $v; 
      $valid[$k] = !preg_match('#[0-9]#',$v); 
      if (!$valid[$k]) { 
          echo "You must enter your last name"; 
      } 
      break;
	case 'birth_year': 
      $data[$k] = $v; 
      $valid[$k] = !preg_match('#[0-9]#',$v); 
      if (!$valid[$k]) { 
          echo "You must enter your birth year"; 
      } 
      break;
	case 'email': 
      $data[$k] = $v; 
      $valid[$k] = !preg_match('#[0-9]#',$v); 
      if (!$valid[$k]) { 
          echo "You must enter a working email address"; 
      } 
      break;
	case 'address': 
      $data[$k] = $v; 
      $valid[$k] = !preg_match('#[0-9]#',$v); 
      if (!$valid[$k]) { 
          echo "You must enter your address"; 
      } 
      break;
	case 'city': 
      $data[$k] = $v; 
      $valid[$k] = !preg_match('#[0-9]#',$v); 
      if (!$valid[$k]) { 
          echo "You must enter your city"; 
      } 
      break;
	case 'state_province': 
      $data[$k] = $v; 
      $valid[$k] = !preg_match('#[0-9]#',$v); 
      if (!$valid[$k]) { 
          echo "You must enter your state or province"; 
      } 
      break;
	case 'zip': 
      $data[$k] = $v; 
      $valid[$k] = !preg_match('#[0-9]#',$v); 
      if (!$valid[$k]) { 
          echo "You must enter your zip or post code"; 
      } 
      break;
	case 'country': 
      $data[$k] = $v; 
      $valid[$k] = !preg_match('#[0-9]#',$v); 
      if (!$valid[$k]) { 
          echo "You must enter your country"; 
      } 
      break;
	case 'continent': 
      $data[$k] = $v; 
      $valid[$k] = !preg_match('#[0-9]#',$v); 
      if (!$valid[$k]) { 
          echo "You must enter your continent"; 
      } 
      break; 
	  
 //   case 'phone': 
//      $data[$k] = $v; 
//      $valid[$k] = ( empty( $v ) ? 1 : preg_match('#^[0-9().-]+$#i',$v) ); 
//      break; 

    default: 
      $data[$k] = $v; 
      $valid[$k] = preg_match 
      break; 
  } 

// log user ip address
$banned = false;
$banlist[] = '';

if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
 $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
else
 $ip = $_SERVER["REMOTE_ADDR"];

$octets1 = explode(".", $ip);
foreach ($banlist as $val){
	$octets2 = explode(".", $val);
	if (	($octets1[0] == $octets2[0] || $octets2[0] == "*") && ($octets1[1] == $octets2[1] || $octets2[1] == "*") && 
		($octets1[2] == $octets2[2] || $octets2[2] == "*") && ($octets1[3] == $octets2[3] || $octets2[3] == "*")){
			$banned = true;
			break;
	}
}

$sql = "insert into street_team (date, first_name, last_name, birth_year, email, address, city, state_province, country, zip, continent, phone, major_city, faves, comments, ip) 
		values ('$date', '$first_name', '$last_name', '$birth_year', '$email', '$address', '$city', '$state_province', '$country', '$zip', '$continent', '$phone', '$major_city', '$faves', '$comments', '$ip')";

  if (!$banned){
  $res = mysql_query($sql,$dbh);
  if (!$res) {
	echo mysql_errno().": ".mysql_error ()."";
	return 0;
	 }
  }
  echo"Submission was successful!";
 
}

?>
Post Reply