Jump to content

how can I apply more than one function to a variable?


co.ador

Recommended Posts

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.

Link to comment
Share on other sites

 

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



}


?>
?>

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.

 

Link to comment
Share on other sites

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).

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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?

 

 

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.