co.ador Posted January 7, 2010 Share Posted January 7, 2010 I am validating a form and want to apply several methods to each one of the five fields in a form. Quote Link to comment https://forums.phpfreaks.com/topic/187570-how-can-i-apply-more-than-one-function-to-a-variable/ Share on other sites More sharing options...
Adam Posted January 7, 2010 Share Posted January 7, 2010 Your question doesn't make much sense. To make things a bit clearer could you show applying just one function to a variable? Edit: Neeee' mind! Quote Link to comment https://forums.phpfreaks.com/topic/187570-how-can-i-apply-more-than-one-function-to-a-variable/#findComment-990311 Share on other sites More sharing options...
KevinM1 Posted January 7, 2010 Share Posted January 7, 2010 I am validating a form and want to apply several methods to each one of the five fields in a form. Chain them together, like you would do in any other scenario: $validatedData = lastValFunction(middleValFunction(firstValFunction($_POST['fieldname']))); So long as your functions return a value, you'll be all set. Quote Link to comment https://forums.phpfreaks.com/topic/187570-how-can-i-apply-more-than-one-function-to-a-variable/#findComment-990312 Share on other sites More sharing options...
co.ador Posted January 7, 2010 Author Share Posted January 7, 2010 Thank you! I guess is the same thing but what I really meant is applying several methods to one parameter. In the example below is the isEmpty method apply to the name parameter. So that's an example of one method applied to one parameter how would be applying several method to one parameter? <?php //open the class validation. include("validationclass.php"); //This are the parameters picked up from the form $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; // instantiate object $fv = new FormValidator(); //test weather name is empty. $fv->isEmpty("name", "Please enter a name");?> Validationclass.php for references. <?php <?php // FormValidator.class.inc // class to perform form validation class FormValidator { // snip // // methods (private) // // function to get the value of a variable (field) function _getValue($field) { global ${$field}; return ${$field}; } // check whether input is empty function isEmpty($field, $msg) { $value = $this->_getValue($field); if (trim($value) == "") { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } // check whether input is a string function isString($field, $msg) { $value = $this->_getValue($field); if(!is_string($value)) { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } // check whether input is a number function isNumber($field, $msg) { $value = $this->_getValue($field); if(!is_numeric($value)) { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } function isInteger($field, $msg) { $value = $this->_getValue($field); if(!is_integer($value)) { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } // check whether input is a float function isFloat($field, $msg) { $value = $this->_getValue($field); if(!is_float($value)) { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } // check whether input is within a valid numeric range function isWithinRange($field, $msg, $min, $max) { $value = $this->_getValue($field); if(!is_numeric($value) || $value < $min || $value > $max) { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } // check whether input is alphabetic function isAlpha($field, $msg) { $value = $this->_getValue($field); $pattern = "/^[a-zA-Z]+$/"; if(preg_match($pattern, $value)) { return true; } else { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } } // check whether input is a valid email address function isEmailAddress($field, $msg) { $value = $this->_getValue($field); $pattern = "/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/ "; if(preg_match($pattern, $value)) { return true; } else { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } } // check whether any errors have occurred in validation // returns Boolean function isError() { if (sizeof($this->_errorList) > 0) { return true; } else { return false; } } // return the current list of errors function getErrorList() { return $this->_errorList; } // reset the error list function resetErrorList() { $this->_errorList = array(); } // constructor // reset error list function FormValidator() { $this->resetErrorList(); } } ?> ?> Quote Link to comment https://forums.phpfreaks.com/topic/187570-how-can-i-apply-more-than-one-function-to-a-variable/#findComment-990358 Share on other sites More sharing options...
KevinM1 Posted January 7, 2010 Share Posted January 7, 2010 To be honest, I'm not quite sure what you're asking. Mind giving an example of what you want to do? Quote Link to comment https://forums.phpfreaks.com/topic/187570-how-can-i-apply-more-than-one-function-to-a-variable/#findComment-990371 Share on other sites More sharing options...
ignace Posted January 7, 2010 Share Posted January 7, 2010 Might not be perfect but gives you a good idea on how you can implement this: interface IValidator { public function isValid($value); } class ValidatorChain implements IValidator { protected $_chain; protected $_messages; protected $_haltOnFirstError = false; public function __construct($haltOnFirstError = false) { $this->_chain = new ArrayObject(); $this->_messages = new ArrayObject(); $this->_haltOnFirstError = $haltOnFirstError; } public function addError($error) { $this->_messages->append($error); } public function addErrors($errors) { foreach ($errors as $error) { $this->addError($error); } } public function getErrors() { return $this->_messages; } public function addValidator(IValidator $validator) { $this->_chain->append($validator); } public function isValid($value) { if (!sizeof($this->_chain)) return true; $valid = true; foreach ($this->_chain as $validator) { if (!$validator->isValid($value)) { $this->addErrors($validator->getErrors()); if ($this->_haltOnFirstError) return false; if ($valid) $valid = false; } } return $valid; } } abstract class ValidatorAbstract implements IValidator { protected $_messages; public function __construct() { $this->_messages = new ArrayObject(); } public function addError($error) { $this->_messages->append($error); } public function getErrors() { return $this->_messages; } } class IsNotEmpty extends ValidatorAbstract { public function isValid($value) { if (empty($value)) { $this->addError("$value is empty"); return false; } return true; } } class IsNumeric extends ValidatorAbstract { public function isValid($value) { if (!is_numeric($value)) { $this->addError("$value is not numeric"); return false; } } return true; } $validator = new ValidatorChain(); $validator->addValidator(new IsNotEmpty()); $validator->addValidator(new IsNumeric()); if (!$validator->isValid('')) { print_r($validator->getErrors()); } Quote Link to comment https://forums.phpfreaks.com/topic/187570-how-can-i-apply-more-than-one-function-to-a-variable/#findComment-990405 Share on other sites More sharing options...
co.ador Posted January 7, 2010 Author Share Posted January 7, 2010 Ignance I am not sure if that's going to make the same effect as this javascript snipet will do frmvalidator.addValidation("Email","maxlen=50"); frmvalidator.addValidation("Email","req"); frmvalidator.addValidation("Email","email"); the javascript email validation above contain three validation to maxlen, required and valid email. It means that if the email goes over 50 characters then it will pop a message that email can not be more than 50 characters, if it is empty then email will be required and or if the email is not a email@host.com format then it will say email is not a valid format. How can i do the same in php? That's why I was asking how can you apply several methods to the same parameter in this case parameter email. Quote Link to comment https://forums.phpfreaks.com/topic/187570-how-can-i-apply-more-than-one-function-to-a-variable/#findComment-990453 Share on other sites More sharing options...
KevinM1 Posted January 7, 2010 Share Posted January 7, 2010 Ignance I am not sure if that's going to make the same effect as this javascript snipet will do frmvalidator.addValidation("Email","maxlen=50"); frmvalidator.addValidation("Email","req"); frmvalidator.addValidation("Email","email"); the javascript email validation above contain three validation to maxlen, required and valid email. It means that if the email goes over 50 characters then it will pop a message that email can not be more than 50 characters, if it is empty then email will be required and or if the email is not a email@host.com format then it will say email is not a valid format. How can i do the same in php? That's why I was asking how can you apply several methods to the same parameter in this case parameter email. Well, just chain your validation functions together, like I already suggested: $email = emailValidator(requiredValidator(lengthValidator($_POST['email'], 50))); Or, design your function to smartly handle all three requirements at once: function emailValidator($field, $maxLen, $req) { if (empty($field) && $req) { // error, field is required } if (strlen($field) > $maxLen) { // error, field value is longer than the max length allowed } //other email validation code (regEx) } $email = emailValidator($_POST['email'], 50, true); The first option is more flexible, as you can reuse the length and required functions on other form fields. Or, if you're comfortable with OOP, you could use the Strategy pattern to help you out (example: http://www.phpfreaks.com/forums/index.php/topic,188111.msg845281.html#msg845281). Quote Link to comment https://forums.phpfreaks.com/topic/187570-how-can-i-apply-more-than-one-function-to-a-variable/#findComment-990463 Share on other sites More sharing options...
co.ador Posted January 7, 2010 Author Share Posted January 7, 2010 i understand the chaining of methods now thank you... i have a question you see how you used [/code]<?php ($_POST['email'], 50) ?>[/code] Can I use a variable instead of the indext? Because I have some extract done that uses the same indexes i am going to use for the validation as below! //Extract the fields['framSearch']['name'] to which are going to be contained in $strName <?php $strName = isset($_POST['frmSearch']['name'])?mysql_real_escape_string($_POST['frmSearch']['name']):'';?> So now can I use $strName like <?php $fv = new FormValidator(); $fv->isEmpty($strName, "Please enter a name"); ?> instead of <?php $fv = new FormValidator(); $fv->isEmpty($_POST['frmSearch']['name'] "Please enter a name"); ?> I am using as below <?php $fv = new FormValidator(); $fv->isEmpty($strName, "Please enter a name"); ?> I did a print_r($_POST) and and a print($strName); and $strName is passing but still it will print an error saying "please enter a name" when it is obviiouly not empty.. what is going on ? help! Quote Link to comment https://forums.phpfreaks.com/topic/187570-how-can-i-apply-more-than-one-function-to-a-variable/#findComment-990492 Share on other sites More sharing options...
KevinM1 Posted January 7, 2010 Share Posted January 7, 2010 Your _getValue() method is gibberish, and is the cause of your error. It doesn't grab the value of the field (I have no idea why you thought putting the 'global' keyword there would do that). Instead, it puts the value of the variable named $field that resides in the global scope in the local $field variable. Since there's likely no such variable in the global scope, you're getting passed a null string, which would make your test fail. For more information: http://us.php.net/manual/en/language.variables.scope.php Quote Link to comment https://forums.phpfreaks.com/topic/187570-how-can-i-apply-more-than-one-function-to-a-variable/#findComment-990540 Share on other sites More sharing options...
co.ador Posted January 8, 2010 Author Share Posted January 8, 2010 I think the method is ok, I have tried the method in another file and it validates. The setup is a little different. Below i extract the indexes without the isset and the if and else statement just variable and $_POST and index like <?php $name = $_POST['name'];?> Then I use the index name inside as the method argument along with the message "please enter your name". It validates perfectly. it won't submit if the field name is not enter? Why in the method is not working? <?php include("validationclass.php"); $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; // instantiate object $fv = new FormValidator(); $fv->isEmpty("name", "Please enter a name"); $fv->isEmpty("email", "Please enter an email"); ?> I was trying to assign the indexes but in the other extraction set up <?php //Extract the fields['framSearch']['name'] to which are going to be contained in $strName $strName = isset($_POST['frmSearch']['name'])?mysql_real_escape_string($_POST['frmSearch']['name']):'';?> as in above it uses an if and else statement pluse the function isset as a difference from <?php $name = $_POST['name'];?> * I use isset and the if and else statement because this function is used in another part of the script. Is there a way I could use the isset and if and else statement way of extracting the index from the form for form validation too? Quote Link to comment https://forums.phpfreaks.com/topic/187570-how-can-i-apply-more-than-one-function-to-a-variable/#findComment-990779 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.