PDA

View Full Version : How Can I Do This?


John_Saunders
09-18-2002, 01:42 AM
I added an error checking section in my form script and I was wondering if somone can help me out. Instead of doing this:

// define fields
$fields = array ('field1', 'field2', 'field3');

// print the error
if (empty($_POST['fields'])) {

$field1_error='Error';
$field2_error='Error';
$field3_error='Error';
etc.
etc.

I would like to make automatically pull the name of each variable and add the _error to it like:

SOMETHING_error='Error'

This way I won't have to make another line for each field.

Any help would be greatly appreciated.


Thanks,

John

firepages
09-18-2002, 09:46 AM
<?
$required=array('field1','field2','field3','etc');

foreach($required as $r){
if(!$_POST[$r]){
${$r."_err"}=1;
$err=1;
}
}

if(!$err){//etc ....
?>


so you end up with the variable '$err' if any error occured and the individual variables '$field1_err' etc... is that what you meant ?

John_Saunders
09-18-2002, 01:33 PM
firepages,

Thanks for your help. Your code helped me make the script so I wouldn't have to define each variable like I had to before, but only now I can't get it to display an error based off my error checking classes. With your script, it just checks to make sure a value is entered, instead of validing a number, e-mail address etc. The code I am using is pasted below. I would really appreciate it if you could tell me how I can make it create the $field_error variable if the value doesn't pass the error checking class.

<?php
if($submit) {

// include class
include("FormValidator.class.inc");

// initiate object
$fv=new FormValidator();

// perform validation
// variables=isEmpty, isString, isNumber, isEmailAddress
$fv->isString("name", "Please enter your \"Name\".");
$fv->isEmailAddress("email","Please enter your \"E-mail Address\".");
$fv->isEmpty("address","Please enter your \"Address\".");

// check for errors
if ($fv->isError())
{
$errors=$fv->getErrorList();

echo "<p class=\"error\">The form could not be submitted because one or more error(s) occurred.</p><p class=\"error\">Please make the changes below and resubmit the form:</p>";
echo "<ul>";
foreach ($errors as $e)
{
echo "<li class=\"error\">" . $e['msg'];
}
echo "</ul>";
}

$required=array('name', 'email', 'address');

foreach($required as $r) {
if(!$_POST[$r]){
${$r."_error"}='style="background-color:#FF0000;"';
$error=1;
}
}

if(!$error) { //add to database, etc.


Here is the validator class that is called from the script that holds my form:

<?php

/*
All source code copyright and proprietary Melonfire, 2002. All content, brand names and trademarks copyright and proprietary Melonfire, 2002. All rights reserved. Copyright infringement is a violation of law.
*/

// FormValidator.class.inc
// class to perform form validation

class FormValidator
{
// private variables

var $_errorList;

// methods (private)

// function to get the value of a variable (field)
function _getValue($field)
{
global ${$field};
return ${$field};
}

// methods (public)

// constructor
// reset error list
function FormValidator()
{
$this->resetErrorList();
}

// 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);
$field_error='style="background-color:#CC0000; color:#FFFFFF;"';
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;
}
}

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

// return the current list of errors
function getErrorList()
{
return $this->_errorList;
}

// check whether any errors have occurred in validation
// returns Boolean
function isError()
{
if (sizeof($this->_errorList) > 0)
{
return true;
}
else
{
return false;
}
}

// reset the error list
function resetErrorList()
{
$this->_errorList = array();
}

// end
}

?>


Thanks again,

John

firepages
09-18-2002, 04:16 PM
Hi, I cant really tie in that class too well with the code I posted... & whilst I think a class just for form validation is OTT - heres a real dodgy one which will work... you just have to create seperate arrays for the different types of validation required i.e. with this sample form data....


<?
$_POST['field1']='t';$_POST['field2']='asdf';
$_POST['field3']='qwer';$_POST['field4']='1234';
$_POST['field5']='s88f@hgjf.gd';$_POST['field6']='123';
$_POST['field7']='sfg@llamas.com';
?>




<?
/*dodgy class*/
class fvalid{
function exists($var=''){
if(trim($var)){
return true;
}else{
return false;
}
}
function nan($var=''){
if(is_numeric(trim($var))){
return true;
}else{
return false;
}
}
function email($var=''){
$pattern = "/^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-]+)+/";
if(preg_match($pattern, $var)){
return true;
}else{
return false;
}
}
}
?>


<?
/*
arrays of fields to be validated...note that the $val array
corresponds to the validation class method
*/
$val[exists]=array('field1','field2','field3','field4');
$val[nan]=array('field6');
$val[email]=array('field5','field7');

/*the messy bit*/
while(list($method,$array)=each($val)){
foreach($array as $r){
$rs=addslashes($_POST[$r]);
if(eval("return(fvalid::$method('$rs'));")==false){
${$r."_err"}=1;
$err=1;
}
}
}
if(!$err){echo "all is well";}else{echo "doh";}
?>


note we are not instansiating any objects here just calling the class method directly with fvalid::method();

John_Saunders
09-18-2002, 04:51 PM
firepages,

Getting rid of the class file and using your method makes a lot more sense. However, I tried out your code and I'm having a few problems.

1. I'm stumped as to what this does or is for:

<?
$_POST['field1']='t';
$_POST['field2']='asdf';
$_POST['field3']='qwer';
$_POST['field4']='1234';
$_POST['field5']='s88f@hgjf.gd';
$_POST['field6']='123';
$_POST['field7']='sfg@llamas.com';
?>

I put it at the top of my error checking section and I'm not sure what goes in the ''s. I put the error messages in the ''s thinking this may be what it is for but they didn't print out.

2. The error descriptions are not being posted. (i.e.)

The following error(s) were found with your submission:

* You forgot to enter your "Name".
* You forgot to enter your "Address".
etc., etc.

How can I display the errors?

3. The class or background color is changing on the form fields even when a correct value is entered. Do you know why it isn't changing it just if there is an error?

/*the messy bit*/
while(list($method,$array)=each($val)){
foreach($array as $r){
$rs=addslashes($_POST[$r]);
if(eval("return(fvalid::$method('$rs'));")==false){
${$r."_error"}='style="background-color:#CC0000; color:#FFFFFF;"';
$error=1;
}
}
}

Thanks again for your help. Sorry if these questions are stupid...but I just started learning PHP.


Regards,

John

firepages
09-18-2002, 06:03 PM
Sorry - the $_POST['field1']='t';$_POST['field2']='asdf'; etc is just simulating form data , (too lazy to write the form:)) and thats probably where the non-error errors came from ?

run the below script as is to see what I mean, then just lose the sample POST data and replace ...

$val[exists]=array('field1','field2','field3','field4');

values with your form field names ('name','email' ... etc

+ I plain forgot about the error messages - see $rets at the bottom of the script.


<?php

/*sample data assume from form*/
$_POST['field1']='t';$_POST['field2']='asdf';
$_POST['field3']='';$_POST['field4']='1234';
$_POST['field5']='s88f@hgjf.gd';$_POST['field6']='123';
$_POST['field7']='dfg';

/*dodgy class*/
class fvalid{
function exists($var=''){
if(trim($var)){
return true;
}else{
return false;
}
}
function nan($var=''){
if(is_numeric(trim($var))){
return true;
}else{
return false;
}
}
function email($var=''){
$pattern = "/^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-]+)+/";
if(preg_match($pattern, $var)){
return true;
}else{
return false;
}
}
}

/*
arrays of fields to be validated...note that the $val array
corresponds to the validation class method
*/
$val[exists]=array('field1','field2','field3','field4');
$val[nan]=array('field6');
$val[email]=array('field5','field7');

/*error messages*/
$errs[exists]=' is a required field';
$errs[nan]=' should be numeric';
$errs[email]=' is not a valid email address';

/*the messy bit*/
while(list($method,$array)=each($val)){
foreach($array as $r){
$rs=addslashes($_POST[$r]);
if(eval("return(fvalid::$method('$rs'));")==false){
${$r."_error"}='style="background-color:#CC0000; color:#FFFFFF;"';
$rets[]=$r.' <b>('.$rs.')</b> '.$errs[$method];
$err=1;
}
}
}


if(!$err){
echo "all is well";
}else{
/*print out error messages*/
foreach($rets as $r){
echo $r."<br />";
}
}
?>

John_Saunders
09-18-2002, 06:21 PM
I tried it out and it is working great! I have few more questions if you don't mind:

1. What does this do and should I post it under where it prints the errors, or within the <html> </html> tags above my form? Is this like a valid referring checker that makes sure the form is being called from my domain?

<?
//if(eval("return(fvalid::$rr('asdfsdf.com'));")==true){echo "true";}else{echo "false";}
?>

2. The errors are currently printing out like:

name () is a required field
address () should be numeric

Is there anyway to get them to show up like and have them show up in order the fields are found in the form?

The following error(s) were found with your submission:

* You forgot to enter your "Name".
* You forgot to enter your "Address".
etc., etc.

3. I'm going to add the form data to a MySQL database and would like to use the code below to make it so nobody can enter any code to cause problems. How can the code below be used along with the code that you posted in your previous post?

Class GetVars{
/* public: construct valid inputs from GET or POST variables
* requires track_vars = on */
function getVars() {
global $HTTP_POST_VARS;
global $HTTP_GET_VARS;
$vars = count($HTTP_POST_VARS) > 0 ? $HTTP_POST_VARS :
(count($HTTP_GET_VARS) > 0 ? $HTTP_GET_VARS : array() );
$cleanvars = array();
reset($vars);
while( list($var, $value) = each($vars) ) {
$cleanvars[$var] = $this->validateInput($value);

}
return $cleanvars;
}

/* private: sanitise a single variable */
function validateInput($var) {
if (get_magic_quotes_gpc()) {
$var = stripslashes($var);
}
$var = strip_tags($var);
$var = htmlspecialchars($var);
$var = str_replace("\n", " ", $var);
$var = str_replace("\r", " ", $var);
$var = trim($var);
return $var;
}

}

Thanks again for everything....I really appreciate your help.


Best Regards,

John

firepages
09-19-2002, 02:22 AM
hi, ignore the code in #1 - thats just me forgetting to remove the junk!

#2 - you can change the error reporting string like so (eg)

$errs[exists]='you forgot to enter your ';

and change this line which formats the message...

$rets[]=$r.' <b>('.$rs.')</b> '.$errs[$method];
to say
$rets[]=$errs[$method].$r;

($r is the field name , $rs is the field value , $errs[$method] is the error string)


#3 - I would probably just change 'the messy bit' to this....


<?
/*the messy bit*/
while(list($method,$array)=each($val)){
foreach($array as $r){
$rs=addslashes(htmlentities(strip_tags($_POST[$r])));
if(eval("return(fvalid::$method('$rs'));")==false){
${$r."_error"}='style="background-color:#CC0000; color:#FFFFFF;"';
$rets[]=$r.' <b>('.$rs.')</b> '.$errs[$method];
$err=1;
}else{
$_POST[$r]=stripslashes($rs);
}
}
}
?>



PS - a general good pointer is not to use a classes as small as the ones you are using :) i.e. they are defeating the point of OO and could much better be realised as functions OR as extentions to some general base classes. (i.e the class I posted above is not really the way to go :))