Jump to content

Simple form validation help required


herghost

Recommended Posts

Hi all, I have the below which is meant to check if the required fields in a form have been submitted, however when submit is clicked, even with no values in the boxes, the form submits as normal.

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include_once ('formvalidator.php');
?>
<link href="../Styles/form_dark.css" rel="stylesheet" type="text/css" />

<?php
$show_form=true;
if(isset($_POST['submit']))
{
    $validator = new FormValidator();
    $validator->addValidation("user_name","req","Please fill in Name");
$validator->addValidation("user_password","req","Please enter a password");
    $validator->addValidation("user_email","email",
"The input for Email should be a valid email value");
    $validator->addValidation("user_email","req","Please fill in Email");
    if($validator->ValidateForm())
    {
        echo "<h2>Validation Success!</h2>";
        $show_form=false;
    }
    else
    {
        echo "<B>Validation Errors:</B>";

        $error_hash = $validator->GetErrors();
        foreach($error_hash as $inpname => $inp_err)
        {
          echo "<p>$inpname : $inp_err</p>\n";
        } 
    }
}

if(true == $show_form)
{
?>	


<form class="dark" action="regdo.php" method="post" >
  <ol>
    <li>
      <fieldset>
        <legend>User Registration</legend>
        <ol>
          <li>
            <label for="user_name">Username</label>
            <input type="text" id="user_name" name="user_name" value="" />
          </li>
          <li>
            <label for="user_email">E-Mail Address</label>
            <input type="text" id="user_email" name="user_email" value="" />
          </li>
          <li>
            <label for="user_password">Password</label>
            <input type="password" id="user_password" name="user_password" value="" />
          </li>
        </ol>
      </fieldset>
    </li>
  </ol>
  <p style="text-align:right;">
    <input type="reset" value="CANCEL" />
    <input type="submit" value="OK" />
  </p>
</form>

<?php
}//true == $show_form
?>

 

Can anyone explain what the problem is?

 

Cheers

 

Link to comment
Share on other sites

Thanks:

<?PHP


/**
* Carries information about each of the form validations
*/
class ValidatorObj
{
var $variable_name;
var $validator_string;
var $error_string;
}

/**
* Base class for custom validation objects
**/
class CustomValidator 
{
function DoValidate(&$formars,&$error_hash)
{
	return true;
}
}

/** Default error messages*/
define("E_VAL_REQUIRED_VALUE","Please enter the value for %s");
define("E_VAL_MAXLEN_EXCEEDED","Maximum length exceeded for %s.");
define("E_VAL_MINLEN_CHECK_FAILED","Please enter input with length more than %d for %s");
define("E_VAL_ALNUM_CHECK_FAILED","Please provide an alpha-numeric input for %s");
define("E_VAL_ALNUM_S_CHECK_FAILED","Please provide an alpha-numeric input for %s");
define("E_VAL_NUM_CHECK_FAILED","Please provide numeric input for %s");
define("E_VAL_ALPHA_CHECK_FAILED","Please provide alphabetic input for %s");
define("E_VAL_ALPHA_S_CHECK_FAILED","Please provide alphabetic input for %s");
define("E_VAL_EMAIL_CHECK_FAILED","Please provide a valida email address");
define("E_VAL_LESSTHAN_CHECK_FAILED","Enter a value less than %f for %s");
define("E_VAL_GREATERTHAN_CHECK_FAILED","Enter a value greater than %f for %s");
define("E_VAL_REGEXP_CHECK_FAILED","Please provide a valid input for %s");
define("E_VAL_DONTSEL_CHECK_FAILED","Wrong option selected for %s");
define("E_VAL_SELMIN_CHECK_FAILED","Please select minimum %d options for %s");
define("E_VAL_SELONE_CHECK_FAILED","Please select an option for %s");
define("E_VAL_EQELMNT_CHECK_FAILED","Value of %s should be same as that of %s");
define("E_VAL_NEELMNT_CHECK_FAILED","Value of %s should not be same as that of %s");



/**
* FormValidator: The main class that does all the form validations
**/
class FormValidator 
{
var $validator_array;
    var $error_hash;
var $custom_validators;

function FormValidator()
{
	$this->validator_array = array();
        $this->error_hash = array();
	$this->custom_validators=array();
}

function AddCustomValidator(&$customv)
{
	array_push($this->custom_validators,$customv);
}

function addValidation($variable,$validator,$error)
{
	$validator_obj = new ValidatorObj();
	$validator_obj->variable_name = $variable;
	$validator_obj->validator_string = $validator;
	$validator_obj->error_string = $error;
	array_push($this->validator_array,$validator_obj);
}
    function GetErrors()
    {
        return $this->error_hash;
    }

function ValidateForm()
{
	$bret = true;

	$error_string="";
	$error_to_display = "";

        
	if(strcmp($_SERVER['REQUEST_METHOD'],'POST')==0)
	{
		$form_variables = $_POST;
	}
	else
	{
		$form_variables = $_GET;
	}

        $vcount = count($this->validator_array);
        

	foreach($this->validator_array as $val_obj)
	{
		if(!$this->ValidateObject($val_obj,$form_variables,$error_string))
		{
			$bret = false;
                $this->error_hash[$val_obj->variable_name] = $error_string;
		}
	}

	if(true == $bret && count($this->custom_validators) > 0)
	{
            foreach( $this->custom_validators as $custom_val)
		{
			if(false == $custom_val->DoValidate($form_variables,$this->error_hash))
			{
				$bret = false;
			}
		}
	}
	return $bret;
}


function ValidateObject($validatorobj,$formvariables,&$error_string)
{
	$bret = true;

	$splitted = explode("=",$validatorobj->validator_string);
	$command = $splitted[0];
	$command_value = '';

	if(isset($splitted[1]) && strlen($splitted[1])>0)
	{
		$command_value = $splitted[1];
	}

	$default_error_message="";

	$input_value ="";

	if(isset($formvariables[$validatorobj->variable_name]))
	{
	 $input_value = $formvariables[$validatorobj->variable_name];
	}

	$bret = $this->ValidateCommand($command,$command_value,$input_value,
								$default_error_message,
								$validatorobj->variable_name,
								$formvariables);


	if(false == $bret)
	{
		if(isset($validatorobj->error_string) &&
			strlen($validatorobj->error_string)>0)
		{
			$error_string = $validatorobj->error_string;
		}
		else
		{
			$error_string = $default_error_message;
		}

	}//if
	return $bret;
}
    	
function validate_req($input_value, &$default_error_message,$variable_name)
{
  $bret = true;
      	if(!isset($input_value) ||
		strlen($input_value) <=0)
	{
		$bret=false;
		$default_error_message = sprintf(E_VAL_REQUIRED_VALUE,$variable_name);
	}	
  return $bret;	
}

function validate_maxlen($input_value,$max_len,$variable_name,&$default_error_message)
{
	$bret = true;
	if(isset($input_value) )
	{
		$input_length = strlen($input_value);
		if($input_length > $max_len)
		{
			$bret=false;
			$default_error_message = sprintf(E_VAL_MAXLEN_EXCEEDED,$variable_name);
		}
	}
	return $bret;
}

function validate_minlen($input_value,$min_len,$variable_name,&$default_error_message)
{
	$bret = true;
	if(isset($input_value) )
	{
		$input_length = strlen($input_value);
		if($input_length < $min_len)
		{
			$bret=false;
			$default_error_message = sprintf(E_VAL_MINLEN_CHECK_FAILED,$min_len,$variable_name);
		}
	}
	return $bret;
}

function test_datatype($input_value,$reg_exp)
{
	if(ereg($reg_exp,$input_value))
	{
		return false;
	}
	return true;
}

function validate_email($email) 
{
	return eregi("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email);
}

function validate_for_numeric_input($input_value,&$validation_success)
{

	$more_validations=true;
	$validation_success = true;
	if(strlen($input_value)>0)
	{

		if(false == is_numeric($input_value))
		{
			$validation_success = false;
			$more_validations=false;
		}
	}
	else
	{
		$more_validations=false;
	}
	return $more_validations;
}

function validate_lessthan($command_value,$input_value,
                $variable_name,&$default_error_message)
{
	$bret = true;
	if(false == $this->validate_for_numeric_input($input_value,
                                    $bret))
	{
		return $bret;
	}
	if($bret)
	{
		$lessthan = doubleval($command_value);
		$float_inputval = doubleval($input_value);
		if($float_inputval >= $lessthan)
		{
			$default_error_message = sprintf(E_VAL_LESSTHAN_CHECK_FAILED,
									$lessthan,
									$variable_name);
			$bret = false;
		}//if
	}
	return $bret ;
}

function validate_greaterthan($command_value,$input_value,$variable_name,&$default_error_message)
{
	$bret = true;
	if(false == $this->validate_for_numeric_input($input_value,$bret))
	{
		return $bret;
	}
	if($bret)
	{
		$greaterthan = doubleval($command_value);
		$float_inputval = doubleval($input_value);
		if($float_inputval <= $greaterthan)
		{
			$default_error_message = sprintf(E_VAL_GREATERTHAN_CHECK_FAILED,
									$greaterthan,
									$variable_name);
			$bret = false;
		}//if
	}
	return $bret ;
}

    function validate_select($input_value,$command_value,&$default_error_message,$variable_name)
    {
    $bret=false;
	if(is_array($input_value))
	{
		foreach($input_value as $value)
		{
			if($value == $command_value)
			{
				$bret=true;
				break;
			}
		}
	}
	else
	{
		if($command_value == $input_value)
		{
			$bret=true;
		}
	}
        if(false == $bret)
        {
            $default_error_message = sprintf(E_VAL_SHOULD_SEL_CHECK_FAILED,
                                            $command_value,$variable_name);
        }
    return $bret;
    }

function validate_dontselect($input_value,$command_value,&$default_error_message,$variable_name)
{
   $bret=true;
	if(is_array($input_value))
	{
		foreach($input_value as $value)
		{
			if($value == $command_value)
			{
				$bret=false;
				$default_error_message = sprintf(E_VAL_DONTSEL_CHECK_FAILED,$variable_name);
				break;
			}
		}
	}
	else
	{
		if($command_value == $input_value)
		{
			$bret=false;
			$default_error_message = sprintf(E_VAL_DONTSEL_CHECK_FAILED,$variable_name);
		}
	}
  return $bret;
}



function ValidateCommand($command,$command_value,$input_value,&$default_error_message,$variable_name,$formvariables)
{
	$bret=true;
	switch($command)
	{
		case 'req':
					{
						$bret = $this->validate_req($input_value, $default_error_message,$variable_name);
						break;
					}

		case 'maxlen':
					{
						$max_len = intval($command_value);
						$bret = $this->validate_maxlen($input_value,$max_len,$variable_name,
											$default_error_message);
						break;
					}

		case 'minlen':
					{
						$min_len = intval($command_value);
						$bret = $this->validate_minlen($input_value,$min_len,$variable_name,
										$default_error_message);
						break;
					}

		case 'alnum':
					{
						$bret= $this->test_datatype($input_value,"[^A-Za-z0-9]");
						if(false == $bret)
						{
							$default_error_message = sprintf(E_VAL_ALNUM_CHECK_FAILED,$variable_name);
						}
						break;
					}

		case 'alnum_s':
					{
						$bret= $this->test_datatype($input_value,"[^A-Za-z0-9 ]");
						if(false == $bret)
						{
							$default_error_message = sprintf(E_VAL_ALNUM_S_CHECK_FAILED,$variable_name);
						}
						break;
					}

		case 'num':
            case 'numeric':
					{
						$bret= $this->test_datatype($input_value,"[^0-9]");
						if(false == $bret)
						{
							$default_error_message = sprintf(E_VAL_NUM_CHECK_FAILED,$variable_name);
						}
						break;							
					}

		case 'alpha':
					{
						$bret= $this->test_datatype($input_value,"[^A-Za-z]");
						if(false == $bret)
						{
							$default_error_message = sprintf(E_VAL_ALPHA_CHECK_FAILED,$variable_name);
						}
						break;
					}
		case 'alpha_s':
					{
						$bret= $this->test_datatype($input_value,"[^A-Za-z ]");
						if(false == $bret)
						{
							$default_error_message = sprintf(E_VAL_ALPHA_S_CHECK_FAILED,$variable_name);
						}
						break;
					}
		case 'email':
					{
						if(isset($input_value) && strlen($input_value)>0)
						{
							$bret= $this->validate_email($input_value);
							if(false == $bret)
							{
								$default_error_message = E_VAL_EMAIL_CHECK_FAILED;
							}
						}
						break;
					}
		case "lt": 
		case "lessthan": 
					{
						$bret = $this->validate_lessthan($command_value,
												$input_value,
												$variable_name,
												$default_error_message);
						break;
					}
		case "gt": 
		case "greaterthan": 
					{
						$bret = $this->validate_greaterthan($command_value,
												$input_value,
												$variable_name,
												$default_error_message);
						break;
					}

		case "regexp":
					{
						if(isset($input_value) && strlen($input_value)>0)
						{
							if(!preg_match("$command_value",$input_value))
							{
								$bret=false;
								$default_error_message = sprintf(E_VAL_REGEXP_CHECK_FAILED,$variable_name);
							}
						}
						break;
					}
	  case "dontselect": 
	  case "dontselectchk":
          case "dontselectradio":
					{
						$bret = $this->validate_dontselect($input_value,
														   $command_value,
														   $default_error_message,
															$variable_name);
						 break;
					}//case

          case "shouldselchk":
          case "selectradio":
                      {
                            $bret = $this->validate_select($input_value,
						       $command_value,
						       $default_error_message,
							    $variable_name);
                            break;
                      }//case
	  case "selmin":
					{
						$min_count = intval($command_value);

						if(isset($input_value))
                            {
						    if($min_count > 1)
						    {
						        $bret = (count($input_value) >= $min_count )?true:false;
						    }
                                else
                                {
                                  $bret = true;
                                }
                            }
						else
						{
							$bret= false;
							$default_error_message = sprintf(E_VAL_SELMIN_CHECK_FAILED,$min_count,$variable_name);
						}

						break;
					}//case
	 case "selone":
					{
						if(false == isset($input_value)||
							strlen($input_value)<=0)
						{
							$bret= false;
							$default_error_message = sprintf(E_VAL_SELONE_CHECK_FAILED,$variable_name);
						}
						break;
					}
	 case "eqelmnt":
					{

						if(isset($formvariables[$command_value]) &&
						   strcmp($input_value,$formvariables[$command_value])==0 )
						{
							$bret=true;
						}
						else
						{
							$bret= false;
							$default_error_message = sprintf(E_VAL_EQELMNT_CHECK_FAILED,$variable_name,$command_value);
						}
					break;
					}
	  case "neelmnt":
					{
						if(isset($formvariables[$command_value]) &&
						   strcmp($input_value,$formvariables[$command_value]) !=0 )
						{
							$bret=true;
						}
						else
						{
							$bret= false;
							$default_error_message = sprintf(E_VAL_NEELMNT_CHECK_FAILED,$variable_name,$command_value);
						}
						break;
					}

	}//switch
	return $bret;
}//validdate command


}

?> 

 

Link to comment
Share on other sites

@teynon

 

Thanks, however no change:

 

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include_once ('formvalidator.php');
?>
<link href="../Styles/form_dark.css" rel="stylesheet" type="text/css" />

<?php
$show_form=true;
if(isset($_POST['submit']))
{
    $validator = new FormValidator();
    $validator->addValidation($_POST['user_name'],"req","Please fill in Name");
$validator->addValidation($_POST['user_password'],"req","Please enter a password");
    $validator->addValidation($_POST['user_email'],"email",
"The input for Email should be a valid email value");
    $validator->addValidation($_POST['user_email'],"req","Please fill in Email");
    if($validator->ValidateForm())
    {
        echo "<h2>Validation Success!</h2>";
        $show_form=false;
    }
    else
    {
        echo "<B>Validation Errors:</B>";

        $error_hash = $validator->GetErrors();
        foreach($error_hash as $inpname => $inp_err)
        {
          echo "<p>$inpname : $inp_err</p>\n";
        } 
    }
}

if(true == $show_form)
{
?>	


<form class="dark" action="regdo.php" method="post" >
  <ol>
    <li>
      <fieldset>
        <legend>User Registration</legend>
        <ol>
          <li>
            <label for="user_name">Username</label>
            <input type="text" id="user_name" name="user_name" value="" />
          </li>
          <li>
            <label for="user_email">E-Mail Address</label>
            <input type="text" id="user_email" name="user_email" value="" />
          </li>
          <li>
            <label for="user_password">Password</label>
            <input type="password" id="user_password" name="user_password" value="" />
          </li>
        </ol>
      </fieldset>
    </li>
  </ol>
  <p style="text-align:right;">
    <input type="reset" value="CANCEL" />
    <input type="submit" value="OK" name="submit" />
  </p>
</form>

<?php
}//true == $show_form
?>

 

@Namtip

 

That would be great if you could :)

 

Thanks

 

 

Link to comment
Share on other sites

This is a registration script from a book I'm using. You send the information from the form into the same file below. it checks if the field is empty. if its empty it sends you back to the form with an error message.

 

if empty example:

<?php
session_start();

include 'db.inc.php';

$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or 
    die ('Unable to connect. Check your connection parameters.');
mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));

$hobbies_list = array('Computers', 'Dancing', 'Exercise', 'Flying', 'Golfing',
    'Hunting', 'Internet', 'Reading', 'Traveling', 'Other than listed');

// filter incoming values
$username = (isset($_POST['username'])) ? trim($_POST['username']) : '';
$password = (isset($_POST['password'])) ? $_POST['password'] : '';
$first_name = (isset($_POST['first_name'])) ? trim($_POST['first_name']) : '';
$last_name = (isset($_POST['last_name'])) ? trim($_POST['last_name']) : '';
$email = (isset($_POST['email'])) ? trim($_POST['email']) : '';
$city = (isset($_POST['city'])) ? trim($_POST['city']) : '';
$state = (isset($_POST['state'])) ? trim($_POST['state']) : '';
$hobbies = (isset($_POST['hobbies']) && is_array($_POST['hobbies'])) ?
    $_POST['hobbies'] : array();

if (isset($_POST['submit']) && $_POST['submit'] == 'Register') {

    $errors = array();

    // make sure manditory fields have been entered
    if (empty($username)) {
        $errors[] = 'Username cannot be blank.';
    }

    // check if username already is registered
    $query = 'SELECT username FROM site_user WHERE username = "' .
        $username . '"';
    $result = mysql_query($query, $db) or die(mysql_error());
    if (mysql_num_rows($result) > 0) {
        $errors[] = 'Username ' . $username . ' is already registered.';
        $username = '';
    }
    mysql_free_result($result);

    if (empty($password)) {
        $errors[] = 'Password cannot be blank.';
    }
    if (empty($first_name)) {
        $errors[] = 'First name cannot be blank.';
    }
    if (empty($last_name)) {
        $errors[] = 'Last name cannot be blank.';
    }
    if (empty($email)) {
        $errors[] = 'Email address cannot be blank.';
    }

    if (count($errors) > 0) {
        echo '<p><strong style="color:#FF000;">Unable to process your ' . 
            'registration.</strong></p>';
        echo '<p>Please fix the following:</p>';
        echo '<ul>';
        foreach ($errors as $error) {
            echo '<li>' . $error . '</li>';
        }
        echo '</ul>';
    } else {
        // No errors so enter the information into the database.

        $query = 'INSERT INTO site_user 
                (user_id, username, password)
           VALUES 
               (NULL, "' . mysql_real_escape_string($username, $db) . '", ' . 
                'PASSWORD("' . mysql_real_escape_string($password, $db) . '"))';
        $result = mysql_query($query, $db) or die(mysql_error());

        $user_id = mysql_insert_id($db);

        $query = 'INSERT INTO site_user_info 
                (user_id, first_name, last_name, email, city, state, hobbies)
           VALUES 
               (' . $user_id . ', ' .
                '"' . mysql_real_escape_string($first_name, $db)  . '", ' .
                '"' . mysql_real_escape_string($last_name, $db)  . '", ' .
                '"' . mysql_real_escape_string($email, $db)  . '", ' .
                '"' . mysql_real_escape_string($city, $db)  . '", ' .
                '"' . mysql_real_escape_string($state, $db)  . '", ' .
                '"' . mysql_real_escape_string(join(', ', $hobbies), $db)  . '")';
        $result = mysql_query($query, $db) or die(mysql_error());

        $_SESSION['logged'] = 1;
        $_SESSION['username'] = $username;

        header('Refresh: 5; URL=main.php');
?>
<html>
<head>
  <title>Register</title>
</head>
<body>
  <p><strong>Thank you <?php echo $username; ?> for registering!</strong></p>
  <p>Your registration is complete! You are being sent to the page you
requested. If your browser doesn't redirect properly after 5 seconds,
<a href="main.php">click here</a>.</p>
</body>
</html>
<?php
        die();
    }
}
?>
<html>
<head>
  <title>Register</title>
  <style type="text/css">
   td { vertical-align: top; }
  </style>
</head>
<body>
  <form action="register.php" method="post">
   <table>
    <tr>
     <td><label for="username">Username:</label></td>
     <td><input type="text" name="username" id="username" size="20"
       maxlength="20" value="<?php echo $username; ?>"/></td>
    </tr><tr>
     <td><label for="password">Password:</label></td>
     <td><input type="password" name="password" id="password" size="20"
       maxlength="20" value="<?php echo $password; ?>"/></td>
    </tr><tr>
     <td><label for="email">Email:</label></td>
     <td><input type="text" name="email" id="email" size="20" maxlength="50"
       value="<?php echo $email; ?>"/></td>
    </tr><tr>
     <td><label for="first_name">First name:</label></td>
     <td><input type="text" name="first_name" id="first_name" size="20"
       maxlength="20" value="<?php echo $first_name; ?>"/></td>
    </tr><tr>
     <td><label for="last_name">Last name:</label></td>
     <td><input type="text" name="last_name" id="last_name" size="20"
       maxlength="20" value="<?php echo $last_name; ?>"/></td>
    </tr><tr>
     <td><label for="city">City:</label></td>
     <td><input type="text" name="city" id="city" size="20" maxlength="20"
       value="<?php echo $city; ?>"/></td>
    </tr><tr>
     <td><label for="state">State:</label></td>
     <td><input type="text" name="state" id="state" size="2" maxlength="2"
       value="<?php echo $state; ?>"/></td>
    </tr><tr>
     <td><label for="hobbies">Hobbies/Interests:</label></td>
     <td><select name="hobbies[]" id="hobbies" multiple="multiple">
<?php
foreach ($hobbies_list as $hobby)
{
    if (in_array($hobby, $hobbies)) {
        echo '<option value="' . $hobby . '" selected="selected">' . $hobby .
            '</option>';
    } else {
        echo '<option value="' . $hobby . '">' . $hobby . '</option>';
    } 
}
?>
      </select></td>
    </tr><tr>
     <td> </td>
     <td><input type="submit" name="submit" value="Register"/></td>
    </tr>
   </table>
  </form>
</body>
</html>

 

obviously that's alright but what if you need something abit more detailed. For example you don't want user(chump) to use a specific character (e.g "*") Then you have to use preg_match and regular expressions(it's hard) :(. Here is an example.

preg_match


<?php

//let's start the session
session_start();

//connect to database
include 'db.inc.php';

$db = mysql_connect('localhost', 'root', '') or 
    die ('Unable to connect. Check your connection parameters.');
mysql_select_db('ourgallery', $db) or die(mysql_error($db));

//finally, let's store our posted values in the session variables
if (isset($_POST['submiti'])) { 
// do something 

$_SESSION['values'] = $_POST;

$error = array();
  
    $query = 'SELECT name FROM user WHERE ' .
         'name = "' . mysql_real_escape_string($_SESSION['values']['name'], $db) . '"' ;
    $result = mysql_query($query, $db) or die(mysql_error($db));

if(mysql_num_rows($result) > 0) {
$error['uname'] = '<p class="errText">Username is taken.</p>';
}
if(  preg_match('/[^a-zA-Z]/',$_SESSION['values']['name']) ) {
$error['name'] = '<p class="errText">Your Username must be made from letters, dashes, spaces and must not start with dash</p>';
}
if(  preg_match('/[^a-zA-Z -]{3,30}/',$_SESSION['values']['first_name']) ) {
$error['first_name'] = '<p class="errText">Your first name must be typed with letters, dashes, spaces and must not start with dash</p>';
}
if(  preg_match('/[^a-zA-Z -]{3,30}/',$_SESSION['values']['last_name']) ) {
$error['last_name'] = '<p class="errText">Your last name must be typed with letters, dashes, spaces and must not start with dash</p>';
}
if(  preg_match('/[^a-zA-Z]\w+(\.\w+)*\@\w+(\.[^0-9a-zA-Z]+)*\.[^a-zA-Z]{2,4}$/',$_SESSION['values']['email']) ) {
$error['email']    = '<p class="errText">This is not a valid email address.';
}
if(  preg_match('/[^a-zA-Z0-9 .,]+$/',$_SESSION['values']['address']) ) {
$error['address'] = '<p class="errText">Address must be only letters, numbers or one of the following ". , : /"</p>';
}
if(  preg_match('/[^a-zA-Z]+/',$_SESSION['values']['city']) ) {
$error['city']    = '<p class="errText">Your city must contain alphabetical characters only.';
}
if(  preg_match('/[^a-zA-Z]+/',$_SESSION['values']['county']) ) {
$error['county']      = '<p class="errText">Your county must contain alphabetical characters only.';
}
if(  preg_match('/(^GIR 0AA)|((([^A-Z-[QVX]][^0-9][^0-9]?)|(([^A-Z-[QVX]][^A-Z-[^IJZ]][^0-9][^0-9]?)|(([^A-Z-[^QVX]][^0-9][^A-HJKSTUW])|([^A-Z-[^QVX]][^A-Z-[^IJZ]][^0-9][^ABEHMNPRVWXY])))) [^0-9][^A-Z-[^CIKMOV]]{2})/',$_SESSION['values']['post']) ) {
$error['post']     = '<p class="errText">This is not a valid UK Postcode.';
}
if(  preg_match('/[^0-9]{1,13}/',$_SESSION['values']['home']) ) {
$error['home']     = '<p class="errText">Your UK local phone number must contain number characters only.';
}
if(  preg_match('/[^0-9]{1,13}/',$_SESSION['values']['mobile']) ) {
$error['mob']     = '<p class="errText">Your UK mobile phone number must contain number characters only.';
}

//if we have errors let's assign them to the session and redirect back, you could just assign to $_SESSION['error']['name'] etc.. above
if(!empty($error)) {
$_SESSION['error'] = $error;
header("Location: form1.php");

exit;

 

That is some of my actual multi page registration script :). Have a look at it and tell me what you don't understand. My response may be sluggish I'm playing counterstrike, so google preg_match and regular expressions if I don't respond immediately.

Link to comment
Share on other sites

@Namtip,

 

many thanks for that! I shall bookmark and keep as a reference, however I would quite like to know w hat is wrong with what I have, never learn if I can't fix it!

 

@teynon,

 

I think that I might know whats wrong, is the script just reading to submit and ignoring the validation?

 

Would I somehow need to have the action perform after the validation has taken place?

 

 

Link to comment
Share on other sites

I've had a look and I'm sorry but I haven't got any knowledge to fall back on with some of the functions you use e.g error_reporting . I'm a bit of a newbie too. If you need any help with my method, I'll respond. Also if there are any php pros on here, could you help with my image upload post. :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.