Jump to content

Recommended Posts

I presume this is the right place to post this question....

 

I have a form which i use validation classes to check the form to make sure correct data is input.  I am trying to come from procedural to OOP and am struggling understanding it.

 

What i want to do is change the color of the text box of all fields that don't validate

Here is my code

 

validation class

<?php
class Validator {
    var $errors;

    function validate($validateThis) {}

    function setError($msg)
    {
$this->errors[] = $msg;
    }

    function isValid()
    {
if (count($this->errors) > 0) {
    return FALSE;
} else {
    return TRUE;
}
    }

    function fetch()
    {
$error = each($this->errors);
if ($error) {
    return $error['value'];
} else {
    reset($this->errors);
    return FALSE;
}
    }
}
?>

an example of one of my validation classes

<?php
    require_once 'includes/php/validators/Validator.php';

    class ValidateTelephone extends Validator {
        function ValidateTelephone ($telephone)
        {
            $this->errors = array();
            $this->validate($telephone);
        } 

    	function validate($telephone)
{
    if(empty($telephone)) {
	$this->setError('Telephone field is empty');
    }
    else {
	if(!preg_match("/(^0[1-9]\d{1}\s\d{4}\s?\d{4}$)|(^0[1-9]\d{2}\s\d{3}\s?\d{4}$)|(^0[1-9]\d{2}\s\d{4}\s?\d{3}$)|(^0[1-9]\d{3}\s\d{3}\s?\d{2}$)|(^0[1-9]\d{3}\s\d{3}\s?\d{3}$)|(^0[1-9]\d{4}\s\d{3}\s?\d{2}$)|(^0[1-9]\d{4}\s\d{2}\s?\d{3}$)|(^0[1-9]\d{4}\s\d{2}\s?\d{2}$)/",$telephone)) {
	    $this->setError('Telephone number in invalid format');
	}
    }
}
    }
?>

 

This is how i used to do it

    function error_bool($error, $field)
    { 
    	if($error[$field]) { 
    print("style=\"background-color:#E7EFFB\""); 
    	} 
    	else {
    print("style=\"background-color:white\"");
    	}
    }

    if(empty($username)) { 
	$error['username'] = true; 
	 $print_again = true; 
	$message.="<li>The <span><b>Username</b></span> field is empty</li>"; 
}

and on the form

<input type="text" <?php error_bool($error, "username"); ?> title="Please enter a username" id="username"

 

i think this is simple enough but don't know how to do it

I don't think a Decorator is required here as validation typically has two functions: to (obviously) validate data, and to inform the user (among others) of incorrect data.  Because of that, I don't think it necessary to remove the 'inform user' functionality from the base validator classes themselves.

 

That said, why not just include two simple get/set functions that deal with the status of the validation?

 

<?php
   class Validator {
      var $errors = array()

      function validate($validateThis) {}

      function setError($msg){
         $this->errors[] = $msg;
      }

      function isValid(){
         if (count($this->errors) > 0) {
            return false;
         } else {
            return true;
         }
      }

      function fetch(){
         if(!$this->errors){
            return false;
         } else{
            foreach($this->errors as $error){
               return $error;
            }
         }
      }
   }

   class ValidateTelephone extends Validator {
      var $status = "style=\"background-color:white\"";

      function ValidateTelephone ($telephone){
         $this->validate($telephone);
         $this->setStatus();
      } 

      function validate($telephone){
         if(empty($telephone)) {
            $this->setError('Telephone field is empty');
         } else {
            if(!preg_match("/(^0[1-9]\d{1}\s\d{4}\s?\d{4}$)|(^0[1-9]\d{2}\s\d{3}\s?\d{4}$)|(^0[1-9]\d{2}\s\d{4}\s?\d{3}$)|(^0[1-9]\d{3}\s\d{3}\s?\d{2}$)|(^0[1-9]\d{3}\s\d{3}\s?\d{3}$)|(^0[1-9]\d{4}\s\d{3}\s?\d{2}$)|(^0[1-9]\d{4}\s\d{2}\s?\d{3}$)|(^0[1-9]\d{4}\s\d{2}\s?\d{2}$)/",$telephone)) {
               $this->setError('Telephone number in invalid format');
            }
         }
      }

      function setStatus(){
         if($this->fetch()){
            $this->status = "style=\"background-color:#E7EFFB\"";
         }
      }

      function getStatus(){
         return $this->status;
      }
   }
?>

 

So, in your client code, assuming you've instantiated a ValidateTelephone object, all you'd need to do is something along the lines of:

<input type="text" <?php echo $validateTelephoneObject->getStatus(); ?> title="Please enter a username" id="username" />

Many thanks  Nightslyr  8)

 

This is what i have been looking for

 

Can you please tell me how i would instantiate a new object like this on my page

 

This is how it's currently done but i have been told that it would be best to put all my validation classes in one file

 

// A array to store errors
    	$errors = array();

    	// Collection of validators
    	$validators = array();

    	$validators[]=new ValidateName($first_name,'Forename');
    	$validators[]=new ValidateName($last_name,'Surname');
    	$validators[]=new ValidateName($street,'Street');
    	$validators[]=new ValidateName($town,'Town/City');
    	$validators[]=new ValidateName($county,'County');
    	$validators[]=new ValidatePostcode($postcode);
    	$validators[]=new ValidateTelephone($telephone);
    	//$validators[]=new ValidateEmail(array($email,$confemail));
   	$validators[]=new ValidateUsername($username);
    	$validators[]=new ValidatePassword(array($pass,$confpass));
$validators[]=new ValidateCaptcha(check_input(trim($_POST['verify']));

    	// Iterate over the validators, validating as we go
    	foreach($validators as $validator) {
    if (!$validator->isValid()) {
	while ( $error = $validator->fetch() ) {
                     $errors[]=$error;
            	}
            }
    	}

 

what i don't get is how i call

<?php echo $validateTelephoneObject->getStatus(); ?>

I can include all the classes into one file like you have done

 

anyway, here is the whole page

<?php

    require_once('includes/php/validators/ValidateName.php');
    require_once('includes/php/validators/ValidateUsername.php');
    require_once('includes/php/validators/ValidatePassword.php');
    require_once('includes/php/validators/ValidatePostcode.php');
    require_once('includes/php/validators/ValidateTelephone.php');
    require_once('includes/php/validators/ValidatePassword.php');
    //require_once('includes/php/validators/ValidateEmail.php');
    require_once('includes/php/validators/ValidateCaptcha.php');

    // Validate the form
    if ( isset ($_POST['register']) ) {

//variables for checking the user's name
    	$first_name = check_input(trim($_POST['first_name']));
    	$last_name = check_input(trim($_POST['last_name']));

    	//variable for checking the user address and telephone
    	$houseno = check_input(trim($_POST['houseno']));
    	$street = check_input(trim($_POST['street']));
    	$town = check_input(trim($_POST['town']));
    	$county = check_input(trim($_POST['county']));
    	$postcode = check_input(trim($_POST['postcode']));
    	$telephone = check_input(trim($_POST['telephone']));

    	//variables for checking the user's email
    	$email = check_input(trim($_POST['email']));
    	$confemail = check_input(trim($_POST['confemail']));

    	// A array to store errors
    	$errors = array();

    	// Collection of validators
    	$validators = array();

    	$validators[]=new ValidateName($first_name,'Forename');
    	$validators[]=new ValidateName($last_name,'Surname');
    	$validators[]=new ValidateName($street,'Street');
    	$validators[]=new ValidateName($town,'Town/City');
    	$validators[]=new ValidateName($county,'County');
    	$validators[]=new ValidatePostcode($postcode);
    	$validators[]=new ValidateTelephone($telephone);
    	//$validators[]=new ValidateEmail(array($email,$confemail));

    	// Iterate over the validators, validating as we go
    	foreach($validators as $validator) {
    if (!$validator->isValid()) {
	while ( $error = $validator->fetch() ) {
                     $errors[]=$error;
            	}
            }
    	}

if(empty($errors)){
    $result = user_register($first_name, $last_name, $houseno, $street, $town, $county, $postcode, $telephone, $email, $username, $pass);
    if ($result == 'Correct') {
    	header('Location: success.php');
    }
    else {
    	$login_error = $result;
    }
        }
    }

    //include the header html with menu etc
    require_once("header.inc.php");

    echo ( "<h2>Register at My Car Share</h2><hr /> ");   

    if (isset($login_error)) { 
echo "There was an error: ".$login_error;
    }

    if ( isset($errors) && count($errors) > 0 ) {
    	echo ( "<h2 class='errorhead'>There has been an error:</h2><p><b>You forgot to enter the following field(s)</b></p>" );
    	echo ( "<ul id='validation'>\n" );
    	foreach ( $errors as $error ) {
    	    echo ( "<li>".$error."</li>\n" );
    	}
echo ( "</ul>\n" );
    }
?>
<form method="post" id="registerForm" name="registerForm" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
    <fieldset>
<legend>About You</legend>
<p><label for="first_name">Forename:</label><label id="first_name_msg" class="valid">Required</label>
<input type="text" title="Please enter your first name" id="first_name" name="first_name" size="28" value="<?php echo $first_name; ?>" class="validate required first_name first_name_msg" /></p>

<p><label for="last_name">Surname:</label><label id="last_name_msg" class="valid">Required</label>
<input type="text" title="Please enter your last name" id="last_name" name="last_name" size="28" value="<?php echo $last_name; ?>" class="validate required last_name last_name_msg" /></p>

<p><label for="last_name">House Name/No. :</label><label id="houseno_msg" class="valid">Required</label>
<input type="text" title="Please enter your last name" id="houseno" name="houseno" size="28" value="<?php echo $houseno; ?>" class="validate required houseno houseno_msg" /></p>

<p><label for="last_name">Street:</label><label id="street_msg" class="valid"></label>
<input type="text" <?php error_bool($error, "street"); ?> title="Please enter your last name" id="street" name="street" size="28" value="<?php echo $street; ?>" class="validate notrequired street street_msg" /></p>

<p><label for="last_name">Town/City:</label><label id="town_msg" class="valid">Required</label>
<input type="text" title="Please enter your last name" id="town" name="town" size="28" value="<?php echo $town; ?>" class="validate required town town_msg" /></p>

<p><label for="last_name">County:</label><label id="county_msg" class="valid"></label>
<input type="text" title="Please enter your last name" id="county" name="county" size="28" value="<?php echo $county; ?>" class="validate notrequired county county_msg" /></p>

<p><label for="postcode">Postcode:</label><label id="postcode_msg" class="valid">Required</label>
<input type="text" title="Please enter your last name" id="postcode" name="postcode" size="28" value="<?php echo $postcode; ?>" class="validate required postcode postcode_msg" /></p>

<p class="hint">Please enter a contact telephone number e.g. 01548 342645</p>
<p><label for="telephone">Telephone:</label><label id="telephone_msg" class="valid">Required</label>
<input type="text" <?php echo $validateTelephoneObject->getStatus(); ?> title="Please enter your last name" id="telephone" name="telephone" size="28" value="<?php echo $telephone; ?>" class="validate required telephone telephone_msg" /></p>

<p class="hint">Please enter a valid email address for yourself.</p>
<p><label for="email">Email:</label><label id="email_msg" class="valid">Required</label>
<input type="text" title="Please enter your email address" id="email" name="email" size="28" value="<?php echo $email; ?>" class="validate required email email_msg" /></p>

<p><label for="confemail">Confirm Email:</label><label id="confemail_msg" class="valid">Required</label>
<input type="text" title="Please enter your email address" id="confemail" name="confemail" size="28" value="" class="validate required confemail confemail_msg" /></p>
    </fieldset>

</form>
<?php
    //include the closing html
    require_once("footer.inc.php");
?>

A few things:

 

If possible, I suggest upgrading to PHP5.  Its OOP capabilities are far better than PHP4's.  In particular, I don't think PHP4 has __autoload(), which is a great built-in PHP function that will autoload the necessary class files automatically, without you needing to manually write all of the include/require statements.  Here's a quick example:

<?php
   function __autoload($className){
      require_once("$className.php");
   }

 

It's as simple as that.  Put the file with the __autoload function in your top-most page/script, and you should be golden.

 

Along those lines, I tend to be a one class per file kind of guy.  Since I'm using __autoload(), that kind of setup works great for me.  However, for PHP4, I can understand trying to streamline class families into one file.  Use whatever works best for you.

 

In terms of instantiating objects, that's actually one of the more difficult things (at least, in my short experience) of OOP.  Without completely dismantling your script, I suggest using a hash.  So, something like:

<?php
   $validators['firstName'] = new ValidateName($first_name, 'Forename');
   .
   .
   .
   $validators['phone'] = new ValidateTelephone($telephone);
   .
   .
   .
   <p><label for="first_name">Forename:</label><label id="first_name_msg" class="valid">Required</label>
<input type="text" <?php echo $validators['firstName']->getStatus(); ?> title="Please enter your first name" id="first_name" name="first_name" size="28" value="<?php echo $first_name; ?>" class="validate required first_name first_name_msg" /></p>
   .
   .
   .
   <p class="hint">Please enter a contact telephone number e.g. 01548 342645</p>
<p><label for="telephone">Telephone:</label><label id="telephone_msg" class="valid">Required</label>
<input type="text" <?php echo $validators['phone']->getStatus(); ?> title="Please enter your last name" id="telephone" name="telephone" size="28" value="<?php echo $telephone; ?>" class="validate required telephone telephone_msg" /></p>

 

It's a bit sloppy, and not really OOP, but something along those lines should probably work.

I have done what you suggested and it made sense but i get this error message and can't find any solution online

 

Call to a member function getStatus() on a non-object

 

Odd...I would think that so long as you assigned a validator object to a specific hash element, it would work.  Which object/line is it referring to?

I just tried it on the input for the telephone number which is 126

 

Am i doing it right....and I have kept all my classes seperate like you suggested and that's the way the book I use does it

<?php
    $title = "Register at mycarshare";
    require_once("includes/php/init.php");

    //if the user has already logged in, redirect them to the edit profile page
    if (is_authed_user() || is_authed_admin())
    {
header('Location: editprofile.php');
    }

    require_once('includes/php/validators/ValidateName.php');
    require_once('includes/php/validators/ValidateUsername.php');
    require_once('includes/php/validators/ValidatePassword.php');
    require_once('includes/php/validators/ValidatePostcode.php');
    require_once('includes/php/validators/ValidateTelephone.php');
    require_once('includes/php/validators/ValidatePassword.php');
    //require_once('includes/php/validators/ValidateEmail.php');
    require_once('includes/php/validators/ValidateCaptcha.php');

    // Validate the form
    if ( isset ($_POST['register']) ) {

//variables for checking the user's name
    	$first_name = check_input(trim($_POST['first_name']));
    	$last_name = check_input(trim($_POST['last_name']));

    	//variable for checking the user address and telephone
    	$houseno = check_input(trim($_POST['houseno']));
    	$street = check_input(trim($_POST['street']));
    	$town = check_input(trim($_POST['town']));
    	$county = check_input(trim($_POST['county']));
    	$postcode = check_input(trim($_POST['postcode']));
    	$telephone = check_input(trim($_POST['telephone']));

    	//variables for checking the user's email
    	$email = check_input(trim($_POST['email']));
    	$confemail = check_input(trim($_POST['confemail']));

    	//varaibles for checking the user login credentials
    	$username = check_input(trim($_POST['username']));
    	$pass = check_input(trim($_POST['pass']));
    	$confpass = check_input(trim($_POST['confpass']));

    	// A array to store errors
    	$errors = array();

    	// Collection of validators
    	$validators = array();

    	$validators[]=new ValidateName($first_name,'Forename');
    	$validators[]=new ValidateName($last_name,'Surname');
    	$validators[]=new ValidateName($street,'Street');
    	$validators[]=new ValidateName($town,'Town/City');
    	$validators[]=new ValidateName($county,'County');
    	$validators[]=new ValidatePostcode($postcode);
    	$validators['phone'] = new ValidateTelephone($telephone);
    	//$validators[]=new ValidateEmail(array($email,$confemail));
   	$validators[]=new ValidateUsername($username);
    	$validators[]=new ValidatePassword(array($pass,$confpass));
$validators[]=new ValidateCaptcha(check_input(trim($_POST['verify'])));

    	// Iterate over the validators, validating as we go
    	foreach($validators as $validator) {
    if (!$validator->isValid()) {
	while ( $error = $validator->fetch() ) {
                     $errors[]=$error;
            	}
            }
    	}

if(empty($errors)){
    $result = user_register($first_name, $last_name, $houseno, $street, $town, $county, $postcode, $telephone, $email, $username, $pass);
    if ($result == 'Correct') {
    	header('Location: success.php');
    }
    else {
    	$login_error = $result;
    }
        }
    }

    //include the header html with menu etc
    require_once("header.inc.php");

    echo ( "<h2>Register at My Car Share</h2><hr /> ");   

    if (isset($login_error)) { 
echo "There was an error: ".$login_error;
    }

    if ( isset($errors) && count($errors) > 0 ) {
    	echo ( "<h2 class='errorhead'>There has been an error:</h2><p><b>You forgot to enter the following field(s)</b></p>" );
    	echo ( "<ul id='validation'>\n" );
    	foreach ( $errors as $error ) {
    	    echo ( "<li>".$error."</li>\n" );
    	}
echo ( "</ul>\n" );
    }
?>
<form method="post" id="registerForm" name="registerForm" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
    <fieldset>
<legend>About You</legend>
<p><label for="first_name">Forename:</label><label id="first_name_msg" class="valid">Required</label>
<input type="text" title="Please enter your first name" id="first_name" name="first_name" size="28" value="<?php echo $first_name; ?>" class="validate required first_name first_name_msg" /></p>

<p><label for="last_name">Surname:</label><label id="last_name_msg" class="valid">Required</label>
<input type="text" title="Please enter your last name" id="last_name" name="last_name" size="28" value="<?php echo $last_name; ?>" class="validate required last_name last_name_msg" /></p>

<p><label for="last_name">House Name/No. :</label><label id="houseno_msg" class="valid">Required</label>
<input type="text" title="Please enter your last name" id="houseno" name="houseno" size="28" value="<?php echo $houseno; ?>" class="validate required houseno houseno_msg" /></p>

<p><label for="last_name">Street:</label><label id="street_msg" class="valid"></label>
<input type="text" <?php error_bool($error, "street"); ?> title="Please enter your last name" id="street" name="street" size="28" value="<?php echo $street; ?>" class="validate notrequired street street_msg" /></p>

<p><label for="last_name">Town/City:</label><label id="town_msg" class="valid">Required</label>
<input type="text" title="Please enter your last name" id="town" name="town" size="28" value="<?php echo $town; ?>" class="validate required town town_msg" /></p>

<p><label for="last_name">County:</label><label id="county_msg" class="valid"></label>
<input type="text" title="Please enter your last name" id="county" name="county" size="28" value="<?php echo $county; ?>" class="validate notrequired county county_msg" /></p>

<p><label for="postcode">Postcode:</label><label id="postcode_msg" class="valid">Required</label>
<input type="text" title="Please enter your last name" id="postcode" name="postcode" size="28" value="<?php echo $postcode; ?>" class="validate required postcode postcode_msg" /></p>

<p class="hint">Please enter a contact telephone number e.g. 01548 342645</p>
<p><label for="telephone">Telephone:</label><label id="telephone_msg" class="valid">Required</label>
<input type="text" <?php echo $validators['phone']->getStatus(); ?> title="Please enter your last name" id="telephone" name="telephone" size="28" value="<?php echo $telephone; ?>" class="validate required telephone telephone_msg" /></p>

<p class="hint">Please enter a valid email address for yourself.</p>
<p><label for="email">Email:</label><label id="email_msg" class="valid">Required</label>
<input type="text" title="Please enter your email address" id="email" name="email" size="28" value="<?php echo $email; ?>" class="validate required email email_msg" /></p>

<p><label for="confemail">Confirm Email:</label><label id="confemail_msg" class="valid">Required</label>
<input type="text" title="Please enter your email address" id="confemail" name="confemail" size="28" value="" class="validate required confemail confemail_msg" /></p>
    </fieldset>

    <fieldset>
<legend>Login details</legend>
<p class="hint">Please enter a username for your account. Note that username should be between 4 and 30 characters and no characters other than letters, numbers, hyphens and underscores may be used.</p>
<p><label for="username">Username:</label><label id="username_msg" class="valid">Required</label>
<input type="text" title="Please enter a username" id="username" name="username" size="28" value="<?php echo $username; ?>" class="validate required username username_msg" /></p>

<p class="hint">Please enter a password for your user account. Note that passwords are case-sensitive. The password must contain at least 6 and no more than 15 characters and no characters other than letters, numbers and underscores may be used</p>
<p><label for="pass">Password:</label><label id="password_msg" class="valid">Required</label>
<input type="password" title="Please enter a password" id="pass" name="pass" size="28" class="validate required pass pass_msg" /></p>

<p><label for="confpass">Confirm password:</label><label id="confpass_msg" class="valid">Required</label>
<input type="password" title="Please re-enter password" id="confpass" name="confpass" size="28" class="validate required confpass confpass_msg" /></p>
    </fieldset>
    <fieldset>
<legend>Image Verification</legend>
    	<p class="hint">Please enter the text that you see in the image into the box below. You are asked to do this in order to verify that this registration is not being performed by an automated process. </p>
    	<div class="captcha2"><img src="includes/php/captcha.php" alt="captcha image" /></div>
    	<p><label for="verify">Anti-Spam key:</label><label id="verify_msg" class="valid">Required</label>
    	<input type="text" title="Please enter the image text" name="verify" id="verify" size="25" class="validate required verify verfify_msg" /></p>
    </fieldset>
    <p><label for="Submit" style="width: 80px"> </label>
    <input type="submit" name="register" value="Complete Registration" class="sendbutton" style="width: 200px"/>
    <input type="reset" value="Reset Fields" class="sendbutton" style="width: 120px"/></p>
</form>
<?php
    //include the closing html
    require_once("footer.inc.php");
?>

Hmm...nothing that would be causing the error is jumping out at me.  I tried a quick test version that checks whether calling the function from the hash directly, as opposed to running it through a foreach-loop, was the culprit.  Both tests worked fine:

<?php
   abstract class Validator{
      private $status = "Everything is good<br />\n";
      private $error;

      function setError($message){
         $this->error = $message;
      }

      function hasError(){
         if($this->error){
            return true;
         } else{
            return false;
         }
      }

      function setStatus(){
         if($this->hasError()){
            $this->status = $this->error;
         }
      }

      function getStatus(){
         return $this->status;
      }
   }

   class NameValidator extends Validator{
      function __construct($name){
         if(preg_match("/^[0-9]*$/", $name)){
            $this->setError("Name's cannot have digits!<br />\n");
         }

         $this->setStatus();
      }
   }

   class TelephoneValidator extends Validator{
      function __construct($phone){
         if(preg_match("/^[a-zA-Z]*$/", $phone)){
            $this->setError("In this test case, phone numbers cannot have letters!<br />\n");
         }

         $this->setStatus();
      }
   }

   $testCases = array();

   $testCases['name'] = new NameValidator("1138");
   $testCases['phone'] = new TelephoneValidator("THX");

   echo "Foreach-loop test:<br /><br />\n\n";

   foreach($testCases as $key => $value){
      echo "Key: $key -- Status: {$value->getStatus()}";
   }

   echo "\n<br />Direct hash calls:<br /><br />\n\n";

   echo "Name status: {$testCases['name']->getStatus()}";
   echo "Phone status: {$testCases['phone']->getStatus()}";
?>

 

Output:

Foreach-loop test:

 

Key: name -- Status: Name's cannot have digits!

Key: phone -- Status: In this test case, phone numbers cannot have letters!

 

Direct hash calls:

 

Name status: Name's cannot have digits!

Phone status: In this test case, phone numbers cannot have letters!

 

These tests were done in PHP5, but I wouldn't think that would make a difference.

 

Have you coded up the set/getStatus functions yet?  Dumb question, I know, but that's really the only thing I can think of at the moment.

I think so

 

You posted some code earlier and i tested it using that

<?php
    require_once 'includes/php/validators/Validator.php';

   class ValidateTelephone extends Validator {
      var $status = "style=\"background-color:white\"";

      function ValidateTelephone ($telephone){
         $this->validate($telephone);
         $this->setStatus();
      } 

      function validate($telephone){
         if(empty($telephone)) {
            $this->setError('Telephone field is empty');
         } else {
            if(!preg_match("/(^0[1-9]\d{1}\s\d{4}\s?\d{4}$)|(^0[1-9]\d{2}\s\d{3}\s?\d{4}$)|(^0[1-9]\d{2}\s\d{4}\s?\d{3}$)|(^0[1-9]\d{3}\s\d{3}\s?\d{2}$)|(^0[1-9]\d{3}\s\d{3}\s?\d{3}$)|(^0[1-9]\d{4}\s\d{3}\s?\d{2}$)|(^0[1-9]\d{4}\s\d{2}\s?\d{3}$)|(^0[1-9]\d{4}\s\d{2}\s?\d{2}$)/",$telephone)) {
               $this->setError('Telephone number in invalid format');
            }
         }
      }

      function setStatus(){
         if($this->fetch()){
            $this->status = "style=\"background-color:#E7EFFB\"";
         }
      }

      function getStatus(){
         return $this->status;
      }
   }
?>

<?php
class Validator {
      var $errors = array();

      function validate($validateThis) {}

      function setError($msg){
         $this->errors[] = $msg;
      }

      function isValid(){
         if (count($this->errors) > 0) {
            return false;
         } else {
            return true;
         }
      }

      function fetch(){
         if(!$this->errors){
            return false;
         } else{
            foreach($this->errors as $error){
               return $error;
            }
         }
      }
   }
?>

Sorry for the delay.

 

I'm still not sure what's causing your error.  I made a PHP4 test case, once again testing different output scenarios, and all variations I tried work.  The class code below is slightly changed -- I made the regex a bit more manageable for a test -- but it is still largely (i.e. 95% or so) what I suggested earlier.

 

<?php
   class Validator {
      var $errors = array();

      function validate($validateThis) {}

      function setError($msg){
         $this->errors[] = $msg;
      }

      function isValid(){
         if ($this->errors) {
            return false;
         } else {
            return true;
         }
      }

      function fetch(){
         if(!$this->errors){
            return false;
         } else{
            foreach($this->errors as $error){
               return $error;
            }
         }
      }
   }

   class ValidateTelephone extends Validator {
      var $status = "Everything okay<br />\n";

      function ValidateTelephone ($telephone){
         $this->validate($telephone);
         $this->setStatus();
      } 

      function validate($telephone){
         if(empty($telephone)) {
            $this->setError('Telephone field is empty');
         } else {
            if(!preg_match("/^[0-9]*$/",$telephone)) {
               $this->setError('Telephone number in invalid format');
            }
         }
      }

      function setStatus(){
         if($this->fetch()){
            $this->status = "Something wrong!<br />\n";
         }
      }

      function getStatus(){
         return $this->status;
      }
   }

   $validators = array();

   $validators['goodNum'] = new ValidateTelephone('1234');
   $validators['badNum'] = new ValidateTelephone('ABCD');

   echo "Direct hash attempt:<br /><br />\n\n";

   echo "Good number status: {$validators['goodNum']->getStatus()}";
   echo "Bad number status: {$validators['badNum']->getStatus()}";

   echo "<br />Foreach-loop test:<br /><br />\n\n";

   foreach($validators as $key => $value){
      echo "Key: $key -- Status: {$value->getStatus()}";
   }

   echo "<br />Embedded into HTML test:<br /><br />\n\n";
?>

   <div>
      Good number status: <?php echo $validators['goodNum']->getStatus(); ?>
      Bad number status: <?php echo $validators['badNum']->getStatus(); ?>
   </div>

 

The output:

Direct hash attempt:

 

Good number status: Everything okay

Bad number status: Something wrong!

 

Foreach-loop test:

 

Key: goodNum -- Status: Everything okay

Key: badNum -- Status: Something wrong!

 

Embedded into HTML test:

 

Good number status: Everything okay

Bad number status: Something wrong!

 

I'm honestly baffled by your error.  The only things I can think of is something not being set properly in the class code, or some syntax error neither of us are picking up on.

I noticed that the class was only being instaniated when the user clicks the submit button.  I have to move it outside so it's called when th epage is loaded....correct?

 

I'm going to have to have another go using your code again becuase for some reason it was timing out trying to load the page so i think i should be able to get it working

 

Thanks for help and I'll let you know later when I give it another go.  hopefully I should have it working

 

BTW I'm using php5 :)

You know what?  That probably is the issue.  On your first page load, nothing has been submitted.  So, you can't get to the validator objects because they don't exist yet.

 

Since you are using PHP5, I strongly suggest you use the __autoload() function to load your class files.  It helps remove logical issues like this by being triggered whenever an unknown object is accessed.  I can't imagine trying to do OOP without it.

I seem to be getting somewhere.

 

When the page first loads the text field is highlighted the error color instead of white...don't know if that's hard to sort out.

 

The main problem is this

 

 

    // Validate the form
    if ( isset ($_POST['register']) ) {

   	// Iterate over the validators, validating as we go
    	foreach($validators as $validator) {
    if (!$validator->isValid()) {
	while ( $error = $validator->fetch() ) {
                     $errors[]=$error;
            	}
      }
}

 

It takes about 30 seconds and dies timin out becasue of the foreach array.

 

What that does is get the error from every validator and adds them to the errors array.

 

Once that is sorted out, hopefully it should work

Hey, sorry for the delay.

 

I think you have too many nested loops.  Try:

<?php
   foreach($validators as $validator){
      if(!$validator->isValid()){ //if there's an error
         $errors[] = $validator->fetch(); //fetch the error and add it to the array
      } //else, do nothing as it's a good result
   }

  if(!empty($errors)){ /* do error notification */ }
?>

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.