Jump to content

New to OOP and classes and need help with code


AdRock

Recommended Posts

This is my first go at OOP using php and I have got an example from a book which is a simple form and it validates the users data

 

I get no errors but it doesn't seem to appear to validate the form

 

Can someone see if i have done something wrong or why it doesn't seem to do anything?

 

Here are my files

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
    <title>Form</title>
</head>
<body>
<b>Please enter your details:</b><br />
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Username: <input type="text" name="user" /><br/>
Password: <input type="password" name="pass" /><br/>
Confirm: <input type="password" name="conf" /><br/>
Email: <input type="text" name="email" /><br/>
<input type="submit" name="submit" value="Submit Form" /><br/>
</form>
<?php 

require_once 'ValidateUser.php';
require_once 'ValidatePassword.php';
require_once 'ValidateEmail.php';

if (isset($_POST['submit'])) {
$errors = array();

$validators = array();
$validators[] = new ValidateUser($_POST['user']);
$validators[] = new ValidatePassword(array($_POST['pass'], $_POST['conf']));
$validators[] = new ValidateEmail($_POST['email']);

foreach ($validators as $validator) {
	if (!$validator->isValid()) {
		while ($error = $validator->fetch()) {
			$errors[] = $error;
		}
	}
}
}
?>
</body>
</html>

 

the validator class

<?php

class Validator {

var $errors;

function Validator($validateThis)
{
	$this->errors = array();
	$this->validate($validateThis);
}

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;
	}
}
}

?>

 

and one of the functions.  I won't post them all becuase they're all similar

<?php
require_once 'Validator.php';

class ValidateUser extends Validator {
	function validate($user)
	{
		if (!preg_match('/^[a-zA-Z0-9_]+$/', $user)) {
			$this->setError('USername contains invalid characters');
		}
		if (strlen($user) < 6) {
			$this->setError('USername is too short');
		}
		if (strlen($user) > 30) {
			$this->setError('USername is too long');
		}
	}
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.