February 21, 201115 yr Hi everyone, I'm having a bit of trouble trying to implement this design pattern for form validation. Here is my code. index.php <?php if (isset( $_POST['register'] )) { //check for existing records $con = mysql_connect("stuff") or die(mysql_error()); mysql_select_db("db", $con) or die(mysql_error()); $result1 = mysql_query("SELECT * FROM blah WHERE username = '$userName'") or die(mysql_error()); $row1 = mysql_fetch_array( $result1 ); $result2 = mysql_query("SELECT * FROM blah WHERE email = '$email1'") or die(mysql_error()); $row2 = mysql_fetch_array( $result2 ); $result3 = mysql_query("SELECT * FROM blah WHERE email = '$email2'") or die(mysql_error()); $row3 = mysql_fetch_array( $result3 ); require_once('validator.php'); // Register the subclasses to use $v['u']=new ValidateUser($userName, $row1); $v['p']=new ValidatePassword($passWord1, $passWord2); $v['e']=new ValidateEmail($email1, $email2, $row2); $v['n']=new ValidateName($firstName, $lastName); // Perform each validation foreach($v as $validator) { if (!$validator->isValid()) { while ($error=$validator->getError()) { $errorMsg.="<li>".$error."</li>"; } } } if (isset($errorMsg)) { echo 'row1 = ' . $row1; echo 'row2 = ' . $row2; print ("<p>There were errors:<ul>".$errorMsg."</ul>"); } else { print ('<h2>Form Valid!</h2>'); } } else { echo' <h2>Create New Account</h2> <form action="http://www.iamcg.co.uk/tests/index.php" method="POST"> <tr> <td><span class="formText">UserName:</span></td> <td><input type="text" name="userName" size="27" /></td> </tr> <tr> <td><span class="formText">First Name:</span></td> <td><input type="text" name="firstName" size="27" /></td> </tr> <tr> <td><span class="formText">Last Name:</span></td> <td><input type="text" name="lastName" size="27" /></td> </tr> <tr> <td><span class="formText">E-mail:</span></td> <td><input type="text" name="email1" size="27" /></td> </tr> <tr> <td><span class="formText">Confirm E-mail:</span></td> <td><input type="text" name="email2" size="27" /></td> </tr> <tr> <td><span class="formText">Password:</span></td> <td><input type="password" name="passWord1" size="27" /></td> </tr> <tr> <td><span class="formText">Confirm Password:</span></td> <td><input type="password" name="passWord2" size="27" /></td> </tr> <tr> <td> </td> </tr> <input type="submit" name="register" value=" Register "> </form> </table> </form>'; } ?> And validator.php <?php /** * Validator superclass for form validation */ class Validator { /** * Private * $errorMsg stores error messages if not valid */ var $errorMsg; //! A constructor. /** * Constucts a new Validator object */ function Validator () { $this->errorMsg=array(); $this->validate(); } //! A manipulator /** * @return void */ function validate() { // Superclass method does nothing } //! A manipulator /** * Adds an error message to the array * @return void */ function setError ($msg) { $this->errorMsg[]=$msg; } //! An accessor /** * Returns true is string valid, false if not * @return boolean */ function isValid () { if ( isset ($this->errorMsg) ) { return false; } else { return true; } } //! An accessor /** * Pops the last error message off the array * @return string */ function getError () { return array_pop($this->errorMsg); } } /** * ValidatorUser subclass of Validator * Validates a username */ class ValidateUser extends Validator { /** * Private * $user the username to validate and the size of our result */ var $userName; var $row1; //! A constructor. /** * Constucts a new ValidateUser object * @param $user the string to validate */ function ValidateUser ($userName, $row1) { $this->user=$userName; $this->size1=$row1; Validator::Validator(); } //! A manipulator /** * Validates a username * @return void */ function validate() { /* if (!preg_match('/^[a-zA-Z0-9]+$/i',$this->user )) { $this->setError('Username contains invalid characters'); } */ if (strlen($this->user) < 5 ) { $this->setError('Username is too short'); } if (strlen($this->user) > 20 ) { $this->setError('Username is too long'); } if ($this->size1 > 0) { $this->setError('Username already in use, please try another'); } } } /** * ValidatorName subclass of Validator * Validates a firstname and surname */ class ValidateName extends Validator { /** * Private * $user the first and last names to validate */ var $firstName; var $lastName; //! A constructor. /** * Constucts a new ValidateUser object * @param $firstName and $lastName the strings to validate */ function ValidateName ($firstName, $lastName) { $this->name1=$firstName; $this->name2=$lastName; Validator::Validator(); } //! A manipulator /** * Validates names * @return void */ function validate() { if (!preg_match('/^[a-zA-Z]+$/i',$this->name1 )) { $this->setError('First name contains invalid characters, only letters allowed'); } if (!preg_match('/^[a-zA-Z]+$/i',$this->name2 )) { $this->setError('Surname contains invalid characters, only letters allowed'); } if (strlen($this->name1) < 2 ) { $this->setError('First name is too short'); } if (strlen($this->name2) < 2 ) { $this->setError('Surname is too short'); } if (strlen($this->name1) > 20 ) { $this->setError('First name is too long'); } if (strlen($this->name2) > 20 ) { $this->setError('Surname is too long'); } } } /** * ValidatorPassword subclass of Validator * Validates a password */ class ValidatePassword extends Validator { /** * Private * $pass the password to validate */ var $passWord1; /** * Private * $conf to confirm the passwords match */ var $passWord2; //! A constructor. /** * Constucts a new ValidatePassword object subclass or Validator * @param $pass the string to validate * @param $conf to compare with $pass for confirmation */ function ValidatePassword ($passWord1,$passWord2) { $this->pass=$passWord1; $this->conf=$passWord2; Validator::Validator(); } //! A manipulator /** * Validates a password * @return void */ function validate() { if ($this->pass!=$this->conf) { $this->setError('Passwords do not match'); } if (!preg_match('/^[a-zA-Z0-9_]+$/',$this->pass)) { $this->setError('Password contains invalid characters'); } if (strlen($this->pass) < 6 ) { $this->setError('Password is too short'); } if (strlen($this->pass) > 20 ) { $this->setError('Password is too long'); } } } /** * ValidatorEmail subclass of Validator * Validates an email address */ class ValidateEmail extends Validator { /** * Private * $email the email address to validate */ var $email1; /** * Private * $email the confirm mail address to validate */ var $email2; /** * Private * query size to checked for duplicates */ var $row2; //! A constructor. /** * Constucts a new ValidateEmail object subclass or Validator * @param $email the string to validate */ function ValidateEmail ($email1, $email2, $row2){ $this->email1=$email1; $this->email2=$email2; $this->size2=$row2; Validator::Validator(); } //! A manipulator /** * Validates an email address * @return void */ function validate() { $pattern= "/^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-]+)+/"; if(!preg_match($pattern,$this->email1)){ $this->setError('Invalid email address'); } if ($this->email1!=$this->email2) { $this->setError('Emails do not match'); } if (strlen($this->email)>30){ $this->setError('Address is too long'); } if ($this->size2 > 0) { $this->setError('Email address already in use, please try another'); } } } ?> I have validation that works perfectly without using the pattern but as soon as I try and implement it with Strategy, it stops working. I can only imagine I'm doing it incorrectly. Any ideas? Cheers, Chris
February 21, 201115 yr Author I'm not sure you need seperate classes to validate each field, as the methods are very similar - if anything, having a seperate class for each field makes things harder to follow and use elsewhere. Why not use have a simple validate field class that extends your main validator class? E.g. class ValidateField extends Validator { . . . . I have seperate classes for different kinds of field. eg. Name Email Password The validation seems to let anything through... :-/
February 21, 201115 yr Author You have several different classes all doing the same thing - totally defeatting the objective of using a class. YOu validate class would simply take the field contents, type of field - you'd then match this against a regex, pgp filter for example. A seperate class for each field, in my opinion is very clumsey way of approaching your problem and is definately not how classes are supposed to be used. I have solved the problem, the variables were not initialised. I'm not sure I'm making myself clear so.... Name Email Password These fields have different constraints (ex. in Name, only a-zA-Z) and require different classes for different constraints.
February 21, 201115 yr I have solved the problem, the variables were not initialised. I'm not sure I'm making myself clear so.... Name Email Password These fields have different constraints (ex. in Name, only a-zA-Z) and require different classes for different constraints. Mmmm i think ur not really getting the idea of classes why create 3 seperate classes to do 3 seperate things, when u could have 1 class say class validator that has seperate functions for these task such as class validator{ public function validate_email(){ } public function validate_password(){ } ect.. } I think this is what rallport means, theres no reason to create a seperate class for such simple task. when all of this could be done using 1 class, also noticed your using a php 4 method why not take advantage of php 5 using public,private, and protected methods Edited February 21, 201115 yr by webdesigner93
February 22, 201115 yr His method is more or less the 'correct' way to implement a validation system based on the strategy pattern.
Create an account or sign in to comment