//--
//-- ToDo:
//-- - Rename to rsPHP
//-- - Accept arrays in validator
//-- - Accept JSON everywhere arrays are accepted
//-------------------------------------------------------------------
//-------------------------------------------
// Class: gapiForms
//
// A class of form tools
//
// Note:
//
// This is different from gapiForm (note the 's' at the end)- this can't initialize a form element, it only contains form related functions
//
//-------------------------------------------
class gapiForms
{
/*
Function: validateError
Validates the information based on the type
Note:
This function is named validateError rather than just validate in order to make the following statement sound more logical
> if ( $myElement->validateError( 'req', $input ) )
> echo "There was an error";
However, even though it's not documented, you can use validateError() and validate() interchangeably without an issue
Parameters:
$type - Type of validation
$input - Information to be validated (Or if custom error, Custom error result)
$val - Value to be validated against (Optional)
Validation Types:
req - Input is required
min - The string must be at least $val characters
max - The string must be less than $val characters
minval - The input must equal at least $val
maxval - The input must equal less than $val
minword - The input must have at least $val words
maxword - The input must have less than $val words
num - The input must be numeric
email - The input must be a valid email address
phone - The input must be a valid phone number
phonea - The input must be a valid phone number with area code
url - The input must be a valid URL
Example:
(start code)
$atLeastError = gapiForms::validateError('min', $input , 3);
$lessThanError = gapiForms::validateError('max', $input , 10);
if ( ! $atLeastError && ! $lessThanError )
echo "This is a valid input!";
elseif ( $atLeastError )
echo $atLeastError;
elseif ( $lessThanError )
echo $lessThanError;
(end)
Example of Custom Validation (No Error):
(start code)
$validate = true;
gapiForms::validateError('customValidation', $validate);
(end)
Example of Custom Validation (Error):
(start code)
$validate = "Error message";
gapiForms::validateError('customValidation', $validate);
(end)
Returns:
Error Message - if an error is found
false - (boolean) if there is no error
*/
function validateError( $type, $input, $val = "" )
{
switch( $type )
{
case "req":
if ( strlen( $input ) == 0 )
$error = "This field is required";
break;
case "min":
if (strlen( $input ) < $val)
$error = "The minimum length is " . $val;
break;
case "max":
if (strlen( $input ) > $val)
$error = "The maximum length is " . $val;
break;
case "minval":
if ( $input < $val )
$error = "The minimum value is " . $val;
break;
case "maxval":
if ( $input > $val )
$error = "The maximum value is " . $val;
break;
case "minword":
if ( str_word_count( $input ) < $val )
$error = "The minimum word count is " . $val;
break;
case "maxword":
if ( str_word_count( $input ) > $val )
$error = "The maximum word count is " . $val;
break;
case "num":
if ( ! is_numeric( $input ) )
$error = "Must be a number";
break;
case "email":
if ( ! eregi( "^[_A-Za-z0-9+-]+(\.[_A-Za-z0-9+-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,4})$" , $input ) )
$error = "Not a valid email address";
break;
case "phone":
$num = preg_replace( '/[^a-zA-Z0-9]/i' , '' , $input );
if ( substr( $num , 0 , 1 ) == 1 )
$num = substr( $num, 1 );
if (! is_numeric( $num ) || ( strlen( $num ) != 10 && strlen( $num ) != 7 ) || substr( $num, -7, 3 ) == 555 )
$error = "Not a valid phone number";
break;
case "phonea":
$num = preg_replace( '/[^a-zA-Z0-9]/i' , '' , $input );
if ( substr( $num , 0 , 1 ) == 1 )
$num = substr( $num, 1 );
if (! is_numeric( $num ) || strlen( $num ) != 10 || substr( $num, -7, 3 ) == 555 )
$error = "Not a valid phone number with area code";
break;
case "url":
if ( ! eregi("^(http|ftp)://(www\.)?.+\.([A-Za-z]{2,4})$" , $input ) )
$error = "Not a valid URL";
break;
default:
$error = $input;
break;
}
if ( $error )
return $error;
else
return false;
}
function validate( $type, $input, $val = "" )
{
return validateError( $type, $input, $val = "" );
}
}
//-------------------------------------------
// Class: gapiElement
//
// An extendable class to add elements to the page
//
// Parameters:
//
// id - The id / name of the element
// options - An array of options (see below)
//
// Options:
//
// value - Default value of the element
// attributes - Attributes of the element
// validate - Things to validate
// autoValidate - Validate without waiting for a submit
//
//-------------------------------------------
class gapiElement
{
var $element;
function gapiElement($id, $type, $options=array())
{
$this->element["id"] = $id;
$this->element["type"] = $type;
$this->element["options"] = $options;
$this->element["attributes"] = $options["attributes"];
unset($options["attributes"]);
if(isset($this->element["options"]["value"]) && ! $this->element["value"])
$this->element["value"] = $this->element["options"]["value"];
unset( $this->element["options"]["value"] );
if(isset($this->element["attributes"]["value"]) && ! $this->element["value"])
$this->element["value"] = $this->element["attributes"]["value"];
unset( $this->element["attributes"]["value"] );
//-- Validate elements
$this->element["validate"] = gapiTools::convertArray( $this->element["options"]["validate"] );
unset($options["validate"]);
if( $this->element["options"]["autoValidate"] )
{
$this->validate();
}
}
/*
Function: get
Get an option's value
Parameters:
option - The option to get
Options:
id - The id/name of the element
type - The type of the element
value - The value of the element
error - The first error to be returned
errors - An array of all errors for the element
validate - An array of all things to be validated
others...- Anything can be stored as an option (ie 'label')
Example:
> echo $element->get('value');
*/
function get($option)
{
switch( $option )
{
case 'id':
return $this->element["id"];
break;
case 'type':
return $this->element["type"];
break;
case 'value':
return $this->element["value"];
break;
case 'error':
return $this->element["errors"][0];
break;
case 'errors':
return $this->element["errors"];
break;
case 'validate':
return $this->element["validate"];
break;
default:
return $this->element["options"][$option];
break;
}
}
/*
Function: set
Set an option's value
Parameters:
option - The option to set (see get() for options)
value - New value of the option
Example:
> $element->set('value', 'New Value!');
*/
function set($option, $value)
{
switch( $option )
{
case 'id':
$this->element["id"] = $value;
break;
case 'type':
$this->element["type"] = $value;
break;
case 'value':
$this->element["value"] = $value;
break;
case 'error':
$this->element["errors"][0] = $value;
break;
case 'validate':
$this->element["validate"] = $value;
break;
case 'errors':
$this->element["errors"] = $value;
break;
default:
$this->element["options"][$option] = $value;
break;
}
}
/*
Function: setAttribute
Set an attribute of the element
Parameters:
attribute - The option to set
value - New value of the option
Example:
> $element->setAttribute('class', 'testClass');
*/
function setAttribute($attribute, $value)
{
$this->element["attributes"][$attribute] = $value;
}
/*
Function: getAttribute
Get an attributes value
Parameters:
attribute - The option to get
Example:
> echo $element->getAttribute('class');
*/
function getAttribute( $attribute )
{
switch( $attribute )
{
case 'id':
return $this->element["id"];
break;
case 'type':
return $this->element["type"];
break;
case 'value':
return $this->element["value"];
break;
default:
return $this->element["attributes"][$attribute];
break;
}
}
/*
Function: validate
Validate an element
Example:
> $textfield = new gapiTextBox( 'newelement',
> array(
> 'value'=>'test',
> 'attributes'=> array(
> 'size'=>5
> )
> ) );
>
> echo $textfield->toString( );
>
> //
Arguments:
$isolate - If true, won't update the error information in the element (optional, defaults to false)
$validate - Array of things to validate (optional, defaults to stored validation preferences for this element)
Returns:
Array of errors (key is validation type, value is error message)
*/
function validate( $isolate = false, $validate = false )
{
$error = false;
if( $validate )
$validate = gapiTools::toArray( $validate );
else
$validate = $this->element["validate"];
foreach( $validate as $k=>$v )
if( gapiForms::validateError( $k, $this->element["value"], $v ) )
$errors[$k] = gapiForms::validateError( $k, $this->element["value"], $v );
if(is_array( $errors ))
$error = array_shift( $errors );
if(is_array( $errors ))
array_unshift( $errors, $error );
if (! $isolate)
{
$this->element["error"] = $error;
$this->element["errors"] = $errors;
}
if( ! $error )
return false;
return gapiTools::toArray( $errors );
}
/*
Function: toString
Outputs a HTML string representation of the element
Example:
> $textfield = new gapiTextBox( 'newelement',
> array(
> 'value'=>'test',
> 'attributes'=> array(
> 'size'=>5
> )
> ) );
>
> echo $textfield->toString( );
>
> //
Arguments:
$return - "start" or "end" (optional, defaults to "both")
Returns:
HTML output
*/
function toString( $return="both" )
{
$inputTypes = array('text', 'hidden', 'submit', 'checkbox');
$attributes = gapiTools::toArray( $this->element["attributes"] );
if( in_array($this->element["type"], $inputTypes) )
{
$type = "input";
$attributes = array( 'type' => $this->element["type"], 'value' => $this->element["value"] ) + $attributes;
}
else
{
$type = $this->element["type"];
$attributes = array( 'type' => $this->element["value"] ) + $attributes;
}
if(! $attributes["name"])
$attributes = array( 'name' => $this->element["id"]) + $attributes;
if(! $attributes["id"])
$attributes = array( 'id' => $this->element["id"]) + $attributes;
foreach($attributes as $k=>$att)
if( trim( $att ) )
$a .= " " . $k . "=\"" . trim( htmlspecialchars( $att , ENT_QUOTES ) ) . "\"";
if( $this->element['type'] == "checkbox" )
if( $this->isChecked() )
$a .= " checked";
if( in_array( $type , array( 'input', 'img' ) ) && $return != "end" )
return "<" . $type . $a . " />";
else
{
if( $return == "start" )
return "<" . $type . $a . ">";
else if( $return == "end" )
return "" . $type . ">";
else
return "<" . $type . $a . ">" . $this->element["value"] . "" . $type . ">";
}
}
}
//-------------------------------------------
// Class: gapiForm
//
// A class to create a form, or utilize form related functions
//
// Extends , has additional functionality specifically for form. Inherits all functions from .
//
// Parameters:
//
// id - The id / name of the form
// elements - Elements of the form
// options - An array of options (see below)
//
// Notes:
//
// Elements must be placed inside the tags manually, or they wont be submitted with the form.
//
// Elements must be passed into the form class before their output is displayed.
//
// Currently isSubmitted() is only true if some sort of information is passed along, which often doesn't meet needs. To ensure that isSubmitted() is always true when the form is submitted, include a hidden field with a default value in your form.
//
// Options:
//
// method - Method of the form, default is "post"
// action - Action of the form (a URL to submit to)
// attributes - Attributes of the element
// validate - Should the form validate its elements? (boolean, default is true)
//
//-------------------------------------------
class gapiForm extends gapiElement
{
function gapiForm( $id, $elements=array(), $options=array() )
{
$this->element["type"] = "form";
$this->element["id"] = $id;
$this->element["elements"] = $elements;
$this->element["options"] = $options;
$this->element["isSubmitted"] = false;
$this->element["isError"] = false;
$this->element["attributes"] = $options["attributes"];
unset($options["attributes"]);
if(! $this->element["options"]["method"])
$this->element["options"]["method"] = "post";
$this->element["attributes"]['method'] = strtolower( $this->element["options"]["method"] );
if( $this->element["options"]["action"] )
$this->element["attributes"]['action'] = $this->element["options"]["action"];
//-- Check if submitted (better way?)
$methodVar = "_" . strtoupper( $this->element["options"]["method"] );
global $$methodVar;
foreach( $elements as $e )
if( ${$methodVar}[ $e->get('id') ] )
$this->element["isSubmitted"] = true;
//-- Stuff to do if submitted
if( $this->element["isSubmitted"] )
{
//-- Set variables (and validate?)
if( $this->element["options"]["validate"] !== false)
{
foreach( $elements as $e )
{
$e->set('value', ${$methodVar}[ $e->get('id') ] );
$isError = $e->validate();
if( $isError )
$this->element["isError"] = true;
}
}
else
{
//-- Set variabes without validating
foreach( $elements as $e )
{
$e->set('value', ${$methodVar}[ $e->get('id') ] );
}
}
}
}
/*
Function: isSubmitted
Check if the form was submitted
Will only work if one of the elements passed into the form is submitted
Example:
(start code)
if( $myForm->isSubmitted( ) )
echo "Congrats! The form was submitted";
else
echo "Please fill out the form";
(end)
Returns:
true - (boolean) if the form was submitted
false - (boolean) if the form was *not* submitted
*/
function isSubmitted( )
{
return $this->element["isSubmitted"];
}
/*
Function: isError
Check if theres an error
Example:
(start code)
if( $myForm->isSubmitted( ) )
{
if( $myForm->isError( ) )
{
echo "There was an error in your submitted form";
}
else
{
echo "Congrats! The form was submitted and there are no errors!";
}
}
else
{
echo "Please fill out the form";
}
(end)
Returns:
true - (boolean) if there is an error
false - (boolean) if there is *no* error
*/
function isError( )
{
return $this->element["isError"];
}
/*
Function: getElements
Returns an array of elements in the form
Returns:
array() - Array of elements if possible
false - If no elements available
*/
function getElements( )
{
return $this->element["elements"];
}
/*
Function: save
Saves the form in a mySQL database
Parameters:
$options - An array of options (see below); optional
Returns:
array() - Array of elements if possible
false - If no elements available
Returns:
true - (boolean) If the data was saved
Error Message (String) - If the data could not be saved
Note:
In regards to the return, to check if the save was successful, you need to use the identity operator (===).
> if( $myForm->save() === true)
> // Means the form was saved
>
> if( $myForm->save() !== true )
> // Means the form was NOT saved
>
> if( $myForm->save() == true)
> //This will always be true
*/
function save( )
{
return $this->element["elements"];
}
}
//-------------------------------------------
// Class: gapiTextBox
//
// Extends , has additional functionality specifically for a textbox. Inherits all functions from .
//
//-------------------------------------------
class gapiTextBox extends gapiElement
{
function gapiTextBox( $id, $options=array() )
{
parent::gapiElement( $id, "text", $options );
}
}
//-------------------------------------------
// Class: gapiSubmit
//
// Extends , has additional functionality specifically for a submit button. Inherits all functions from .
//
//-------------------------------------------
class gapiSubmit extends gapiElement
{
function gapiSubmit( $id, $options=array() )
{
parent::gapiElement( $id, "submit", $options );
}
}
//-------------------------------------------
// Class: gapiChoice
//
// Extends , has additional functionality specifically for a drop down menu choice. Inherits all functions from .
//
// The syntax for creating a choice is different from the other elements, though
//
// Syntax:
//
// > $choice = new gapiChoice( "Value", "Display Text", $options);
//
// Produces
//
// >
//
// Syntax (Value only):
//
// (No options allowed)
//
// > $choice = new gapiChoice( "Value" );
//
// Produces
//
// >
//
//-------------------------------------------
class gapiChoice extends gapiElement
{
function gapiChoice( $value, $display, $options=array() )
{
if( $display === true )
$display = $value;
$options["value"] = $value;
$options["display"] = $display;
parent::gapiElement( null, "option", $options );
}
}
//-------------------------------------------
// Class: gapiHidden
//
// Extends , has additional functionality specifically for a hidden textbox. Inherits all functions from .
//
//-------------------------------------------
class gapiHidden extends gapiElement
{
function gapiHidden( $id, $options=array() )
{
parent::gapiElement( $id, "hidden", $options );
}
}
//-------------------------------------------
// Class: gapiTextArea
//
// Extends , has additional functionality specifically for a textarea. Inherits all functions from .
//
//-------------------------------------------
class gapiTextArea extends gapiElement
{
function gapiTextArea( $id, $options=array() )
{
parent::gapiElement( $id, "textarea", $options );
}
}
//-------------------------------------------
// Class: gapiCheckBox
//
// Extends , has additional functionality specifically for a checkbox. Inherits all functions from .
//
//-------------------------------------------
class gapiCheckBox extends gapiElement
{
function gapiCheckBox( $id, $options=array() )
{
parent::gapiElement( $id, "checkbox", $options );
}
function isChecked( )
{
if($this->get("value"))
return true;
}
}
?>