Package: Generic

Class: Zebra_Form_Control

source file: /includes/Control.php

Class Overview

XSS_Clean
|
--Zebra_Form_Control

A generic class containing common methods, shared by all the controls.

Author(s):

Copyright:

  • (c) 2006 - 2016 Stefan Gabos

Inherited methods

Class: XSS_Clean

XSS_Clean::sanitize()
Sanitizes submitted data so that Cross Site Scripting Hacks can be prevented.

Child classes:

Zebra_Form_Button
Class for button controls.
Zebra_Form_Captcha
Class for CAPTCHA controls.
Zebra_Form_Checkbox
Class for checkbox controls.
Zebra_Form_Date
Class for date controls.
Zebra_Form_File
Class for file upload controls.
Zebra_Form_Hidden
Class for hidden controls.
Zebra_Form_Image
Class for image controls.
Zebra_Form_Label
Class for labels
Zebra_Form_Note
Class for notes attached to controls
Zebra_Form_Password
Class for password controls.
Zebra_Form_Radio
Class for radio button controls.
Zebra_Form_Reset
Class for reset button controls.
Zebra_Form_Select
Class for select box controls.
Zebra_Form_Submit
Class for submit controls.
Zebra_Form_Text
Class for text controls.
Zebra_Form_Textarea
Class for textarea controls
Zebra_Form_Time
Class for time picker controls.

Class properties

array $attributes

Array of HTML attributes of the element

Tags:
access: public
Top

array $private_attributes

Array of HTML attributes that the control's render_attributes() method should skip

Tags:
access: public
Top

array $rules

Array of validation rules set for the control

Tags:
access: public
Top

Class methods

method change_case()

void change_case ( string $case )

Call this method to instruct the script to force all letters typed by the user, to either uppercase or lowercase, in real-time.

Works only on text, textarea and password controls.

  1. // create a new form
  2. $form new Zebra_Form('my_form');
  3.  
  4. // add a text control to the form
  5. $obj $form->add('text''my_text');
  6.  
  7. // entered characters will be upper-case
  8. $obj->change_case('upper');
  9.  
  10. // don't forget to always call this method before rendering the form
  11. if ($form->validate()) {
  12.     // put code here
  13. }
  14.  
  15. // output the form using an automatically generated template
  16. $form->render();
Tags:
since: 2.8
Parameters:
string $case

The case to convert all entered characters to.

Can be (case-insensitive) "upper" or "lower".

Top

method disable_spam_filter()

void disable_spam_filter ( )

Disables the SPAM filter for the control.

By default, for checkboxes, radio buttons and select boxes, the library will prevent the submission of other values than those declared when creating the form, by triggering the error: "SPAM attempt detected!". Therefore, if you plan on adding/removing values dynamically, from JavaScript, you will have to call this method to prevent that from happening.

Works only for checkbox, radio and select controls.

Top

method disable_xss_filters()

void disable_xss_filters ( )

Disables XSS filtering of the control's submitted value.

By default, all submitted values are filtered for XSS (Cross Site Scripting) injections. The script will automatically remove possibly malicious content (event handlers, javascript code, etc). While in general this is the right thing to do, there may be the case where this behaviour is not wanted: for example, for a CMS where the WYSIWYG editor inserts JavaScript code.

  1. // $obj is a reference to a control
Top

method get_attributes()

array get_attributes ( mixed $attributes )

Returns the values of requested attributes.

  1. // create a new form
  2. $form new Zebra_Form('my_form');
  3.  
  4. // add a text field to the form
  5. $obj $form->add('text''my_text');
  6.  
  7. // set some attributes for the text field
  8. $obj->set_attributes(array(
  9.     'readonly'  => 'readonly',
  10.     'style'     => 'font-size:20px',
  11. ));
  12.  
  13. // retrieve the attributes
  14. $attributes $obj->get_attributes(array('readonly''style'));
  15.  
  16. // the result will be an associative array
  17. //
  18. // $attributes = Array(
  19. //      [readonly]  => "readonly",
  20. //      [style]     => "font-size:20px"
  21. // )
Tags:
return: Returns an associative array where keys are the attributes and the values are each attribute's value, respectively.
Parameters:
mixed $attributes A single or an array of attributes for which the values to be returned.
Top

method lock()

void lock ( )

Locks the control's value. A locked control will preserve its default value after the form is submitted even if the user altered it.

This doesn't mean that the submitted value will be the default one! It will still be the one selected by the user, but when and if the form is repainted, the value shown in the control will be the locked one, not the one selected by the user

  1. // $obj is a reference to a control
  2. $obj->lock();
Top

method reset()

void reset ( )

Resets the control's submitted value (empties text fields, unchecks radio buttons/checkboxes, etc).

This method also resets the associated POST/GET/FILES superglobals!

  1. // $obj is a reference to a control
  2. $obj->reset();
Top

method set_attributes()

void set_attributes ( array $attributes , [ boolean $overwrite = true] )

Sets one or more of the control's attributes.

  1. // create a new form
  2. $form new Zebra_Form('my_form');
  3.  
  4. // add a text field to the form
  5. $obj $form->add('text''my_text');
  6.  
  7. // set some attributes for the text field
  8. $obj->set_attributes(array(
  9.     'readonly'  => 'readonly',
  10.     'style'     => 'font-size:20px',
  11. ));
  12.  
  13. // retrieve the attributes
  14. $attributes $obj->get_attributes(array('readonly''style'));
  15.  
  16. // the result will be an associative array
  17. //
  18. // $attributes = Array(
  19. //      [readonly]  => "readonly",
  20. //      [style]     => "font-size:20px"
  21. // )
Parameters:
array $attributes An associative array, in the form of attribute => value.
boolean $overwrite

Setting this argument to FALSE will instruct the script to append the values of the attributes to the already existing ones (if any) rather then overwriting them.

Useful, for adding an extra CSS class to the already existing ones.

For example, the text control has, by default, the class attribute set and already containing some classes needed both for styling and for JavaScript functionality. If there's the need to add one more class to the existing ones, without breaking styles nor functionality, one would use:

  1. // obj is a reference to a control
  2. $obj->set_attributes(array('class'=>'my_class')false);

Default is TRUE

Top

method set_rule()

void set_rule ( array $rules )

Sets a single or an array of validation rules for the control.

  1. // $obj is a reference to a control
  2. $obj->set_rule(array(
  3.     'rule #1'    =>  array($arg1$arg2... $argn),
  4.     'rule #2'    =>  array($arg1$arg2... $argn),
  5.     ...
  6.     ...
  7.     'rule #n'    =>  array($arg1$arg2... $argn),
  8. ));
  9. // where 'rule #1', 'rule #2', 'rule #n' are any of the rules listed below
  10. // and $arg1, $arg2, $argn are arguments specific to each rule

When a validation rule is not passed, a variable becomes available in the template file, having the name as specified by the rule's error_block argument and having the value as specified by the rule's error_message argument.

Validation rules are checked in the given order, the exceptions being the "dependencies", "required" and "upload" rules, which are *always* checked in the order of priority: "dependencies" has priority over "required" which in turn has priority over "upload".

I usually have at the top of my custom templates something like (assuming all errors are sent to an error block named "error"):

  1. echo (isset($zf_error$zf_error (isset($error$error ''));

The above code nees to be used only for custom templates, or when the output is generated via callback functions! For automatically generated templates it is all taken care for you automatically by the library! Notice the $zf_error variable which is automatically created by the library if there is a SPAM or a CSRF error! Unless you use it, these errors will not be visible for the user. Again, remember, we're talking about custom templates, or output generated via callback functions.

One or all error messages can be displayed in an error block. See the show_all_error_messages() method.

Everything related to error blocks applies only for server-side validation.
See the client_side_validation() method for configuring how errors are to be displayed to the user upon client-side validation.

Available rules are

  • age
  • alphabet
  • alphanumeric
  • captcha
  • compare
  • convert
  • custom
  • date
  • datecompare
  • dependencies
  • digits
  • email
  • emails
  • filesize
  • filetype
  • float
  • image
  • length
  • number
  • range
  • regexp
  • required
  • resize
  • upload
  • url

Rules description:

  • age
  1. 'age' => array($range$error_block$error_message)

where

  • range is an array with 2 values, representing the minimum and maximum age allowed. 0 (zero) means "any age". Therefore, a range of array(21, 0) would validate ages above 20, array(6, 12) would validate ages between 6 and 12 (inclusive), while (0, 12) would validate ages below 13

  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed
Validates if the difference in years between the current date and the date entered in the control is whitin the allowed range

Available for the following controls: text

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'age' => array(
  4.         array(210)            // allow ages above 20
  5.         'error',                // variable to add the error message to
  6.         'Age must be above 20'  // error message if value doesn't validate
  7.      )
  8. );

  • alphabet
  1. 'alphabet' => array($additional_characters$error_block$error_message)

where

  • additional_characters is a list of additionally allowed characters besides the alphabet (provide an empty string if none); note that if you want to use / (backslash) you need to specify it as three (3) backslashes ("///")!

  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed
Validates if the value contains only characters from the alphabet (case-insensitive a to z) plus characters given as additional characters (if any).

Available for the following controls: password, text, textarea

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'alphabet' => array(
  4.         '-'                                     // allow alphabet plus dash
  5.         'error',                                // variable to add the error message to
  6.         'Only alphabetic characters allowed!'   // error message if value doesn't validate
  7.      )
  8. );

  • alphanumeric
  1. 'alphanumeric' => array($additional_characters$error_block$error_message)

where

  • additional_characters is a list of additionally allowed characters besides the alphabet and digits 0 to 9 (provide an empty string if none); note that if you want to use / (backslash) you need to specify it as three (3) backslashes ("///")!

  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed
Validates if the value contains only characters from the alphabet (case-insensitive a to z) and digits (0 to 9) plus characters given as additional characters (if any).

Available for the following controls: password, text, textarea

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'alphanumeric' => array(
  4.         '-',                                    // allow alphabet, digits and dash
  5.         'error',                                // variable to add the error message to
  6.         'Only alphanumeric characters allowed!' // error message if value doesn't validate
  7.      )
  8. );

  • captcha
  1. 'captcha' => array($error_block$error_message)

where

  • error_block is the PHP variable to append the error message to, in case the rule does not validate

  • error_message is the error message to be shown when rule is not obeyed
Validates if the value matches the characters seen in the captcha image (therefore, there must be a captcha image on the form)

Available only for the text control

This rule is not available client-side!

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'captcha' => array(
  4.         'error',                            // variable to add the error message to
  5.         'Characters not entered correctly!' // error message if value doesn't validate
  6.      )
  7. );

  • compare
  1. 'compare' => array($control$error_block$error_message)

where

  • control is the name of a control on the form to compare values with

  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed
Validates if the value is the same as the value of the control indicated by control.

Useful for password confirmation.

Available for the following controls: password, text, textarea

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'compare' => array(
  4.         'password'                          // name of the control to compare values with
  5.         'error',                            // variable to add the error message to
  6.         'Password not confirmed correctly!' // error message if value doesn't validate
  7.      )
  8. );

  • convert
This rule requires the prior inclusion of the Zebra_Image library!

  1. 'convert' => array($type$jpeg_quality$preserve_original_file$overwrite$error_block$error_message)

where

  • type the type to convert the image to; can be (case-insensitive) JPG, PNG or GIF

  • jpeg_quality: Indicates the quality of the output image (better quality means bigger file size).
Range is 0 - 100

Available only if type is "jpg".

  • preserve_original_file: Should the original file be preserved after the conversion is done?
  • $overwrite: If a file with the same name as the converted file already exists, should it be overwritten or should the name be automatically computed.

If a file with the same name as the converted file already exists and this argument is FALSE, a suffix of "_n" (where n is an integer) will be appended to the file name.

  • error_block is the PHP variable to append the error message to, in case the rule does not validate

  • error_message is the error message to be shown when rule is not obeyed
This rule will convert an image file uploaded using the upload rule from whatever its type (as long as is one of the supported types) to the type indicated by type.

Validates if the uploaded file is an image file and type is valid.

This is not actually a "rule", but because it can generate an error message it is included here

You should use this rule in conjunction with the upload and image rules.

If you are also using the resize rule, make sure you are using it AFTER the convert rule!

Available only for the file control

This rule is not available client-side!

  1. // $obj is a reference to a file upload control
  2. $obj->set_rule(
  3.      'convert' => array(
  4.         'jpg',                          // type to convert to
  5.         85,                             // converted file quality
  6.         false,                          // preserve original file?
  7.         false,                          // overwrite if converted file already exists?
  8.         'error',                        // variable to add the error message to
  9.         'File could not be uploaded!'   // error message if value doesn't validate
  10.      )
  11. );

  • custom

Using this rule, custom rules can be applied to the submitted values.

  1. 'custom'=>array($callback_function_name[optional arguments to be passed to the function]$error_block$error_message)

where

  • callback_function_name is the name of the callback function
  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed
The callback function's first argument must ALWAYS be the control's submitted value. The optional arguments to be passed to the callback function will start as of the second argument!

The callback function MUST return TRUE on success or FALSE on failure!

Multiple custom rules can also be set through an array of callback functions:

  1. 'custom' => array(
  2.  
  3.     array($callback_function_name1[optional arguments to be passed to the function]$error_block$error_message),
  4.     array($callback_function_name1[optional arguments to be passed to the function]$error_block$error_message)
  5.  
  6. )

If client-side validation is enabled (enabled by default), the custom function needs to also be available in JavaScript, with the exact same name as the function in PHP!

For example, here's a custom rule for checking that an entered value is an integer, greater than 21:

  1. // the custom function in JavaScript
  2. <script type="text/javascript">
  3.     function is_valid_number(value)
  4.     {
  5.         // return false if the value is less than 21
  6.         if (value 21return false;
  7.         // return true otherwise
  8.         return true;
  9.     }
  10. </script>

  1. // the callback function in PHP
  2. function is_valid_number($value)
  3. {
  4.     // return false if the value is less than 21
  5.     if ($value 21return false;
  6.     // return true otherwise
  7.     return true;
  8. }
  9.  
  10. // create a new form
  11. $form new Zebra_Form('my_form');
  12.  
  13. // add a text control to the form
  14. $obj $form->add('text''my_text');
  15.  
  16. // set two rules:
  17. // on that requires the value to be an integer
  18. // and a custom rule that requires the value to be greater than 21
  19. $obj->set_rule(
  20.     'number'    =>  array('''error''Value must be an integer!'),
  21.     'custom'    =>  array(
  22.         'is_valid_number',
  23.         'error',
  24.         'Value must be greater than 21!'
  25.     )
  26. );

And here's how I do validations using AJAX:

In my website's main JavaScript file I have something like:

  1. var valid null;
  2.  
  3. // I have functions like these for everything that I need checked through AJAX; note that they are in the global
  4. // namespace and outside the DOM-ready event
  5.  
  6. // functions have to return TRUE in order for the rule to be considered as obeyed
  7. function username_not_taken(username{
  8.     $.ajax({data'username=' username});
  9.     return valid;
  10. }
  11.  
  12. function emailaddress_not_taken(email{
  13.     $.ajax({data'email=' email});
  14.     return valid;
  15. }
  16.  
  17. // in the DOM ready event
  18. $(document).ready(function({
  19.  
  20.     // I setup an AJAX object that will handle all my AJAX calls
  21.     $.ajaxSetup({
  22.         url'path/to/validator/',  // actual work will be done in PHP
  23.         type'post',
  24.         dataType'text',
  25.         asyncfalse,               // this is important!
  26.         globalfalse,
  27.         beforeSendfunction({
  28.             valid null;
  29.         },
  30.         successfunction(datatextStatus{
  31.             if (data == 'valid'valid true;
  32.             else valid false;
  33.         }
  34.     });
  35.  
  36.     // ...other JavaScript code for your website...
  37.  
  38. }

I also have a "validation.php" "helper" file which contains the PHP functions that do the actual checkings. This file is included both in the page where I create the form (used by the server-side validation) and also by the file defined by the "url" property of the AJAX object (used for client-side validation). This might look something like:

  1. function username_not_taken($username{
  2.     // check for username and return TRUE if it's NOT taken, or FALSE otherwise
  3. }
  4.  
  5. function emailaddress_not_taken($email{
  6.     // check for email address and return TRUE if it's NOT taken, or FALSE otherwise
  7. }

As stated above, when I create a form I include this "helper" file at the top, because the functions in it will be used by the server-side validation, and set the custom rules like this:

  1. $obj->set_rule(array(
  2.     'custom'  =>  array(
  3.         'username_not_taken',
  4.         'error',
  5.         'This user name is already taken!'
  6.     ),
  7. ));

...and finally, at the "url" set in the AJAX object, I have something like:

  1. // include the "helper" file
  2. require 'path/to/validation.php';
  3.  
  4. if (
  5.  
  6.     // make sure it's an AJAX request
  7.     isset($_SERVER['HTTP_X_REQUESTED_WITH']&&
  8.  
  9.     // make sure it has a referrer
  10.     isset($_SERVER['HTTP_REFERER']&&
  11.  
  12.     // make sure it comes from your website
  13.     strpos($_SERVER['HTTP_REFERER']'your/website/base/url'=== 0
  14.  
  15. {
  16.  
  17.     if (
  18.  
  19.         // i run functions depending on what's in the $_POST and also make some extra sanity checks
  20.         (isset($_POST['username']&& count($_POST== && username_not_taken($_POST['username'])) ||
  21.         (isset($_POST['email']&& count($_POST== && emailaddress_not_taken($_POST['email']))
  22.  
  23.     // if whatever I'm checking is OK, I just echo "valid"
  24.     // (this will be later used by the AJAX object)
  25.     echo 'valid';
  26.  
  27. }
  28.  
  29. // do nothing for any other case

  • date
  1. 'date' => array($error_block$error_message)

where

  • error_block is the PHP variable to append the error message to, in case the rule does not validate

  • error_message is the error message to be shown when rule is not obeyed
Validates if the value is a propper date, formated according to the format set through the format() method.

Available only for the date control.

Note that the validation is language dependant: if the form's language is other than English and month names are expected, the script will expect the month names to be given in that particular language, as set in the language file!

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'date' => array(
  4.         'error',        // variable to add the error message to
  5.         'Invalid date!' // error message if value doesn't validate
  6.      )
  7. );

  • datecompare
  1. 'datecompare' => array($control$comparison_operator$error_block$error_message)

where

  • control is the name of a date control on the form to compare values with
  • comparison_operator indicates how the value should be, compared to the value of control.
    Possible values are <, <=, >, >=

  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed
Validates if the value satisfies the comparison operator when compared to the other date control's value.

Available only for the date control.

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'datecompare' => array(
  4.         'another_date'                      // name of another date control on the form
  5.         '>',                                // comparison operator
  6.         'error',                            // variable to add the error message to
  7.         'Date must be after another_date!'  // error message if value doesn't validate
  8.      )
  9. );

  • dependencies
  1. 'dependencies' => array($conditions)

or

  1. 'dependencies' => array(array($conditions)'callback_function_name[, arguments]')

where

  • $conditions an array of associative arrays where the keys represent the names of form controls (remember: names, not IDs, and without the square brackets ([]) used for checkbox groups and multiple selects), while the associated value/values represent the value/values that those controls need to have in order for the current control to be validated. Notable exceptions are the submit and image elements, where the associated value must *always* be "click".

Only when all conditions are met, the control's other rules will be checked!

  • callback_function_name is the name of an existing JavaScript function which will be executed whenever the value of any of the controls listed in the "dependencies" rule changes - useful for showing/hiding controls that depend on the values of other controls.

An element's other existing rules will be checked only if this rule is passed.

Conditions can be applied to an infinite depth and will be checked accordingly - so, a control may depend on another control which, in turn, may depend on another control and so on, and all this will be automatically taken care of: say control C depends on control B having the value "1", while control B depends on control A having the value "2"; now, even if B has the value "1", as long as A doesn't have the value "2", control C will not be validated.

The library will terminate exection and will trigger an error message if an infinite loop of dependencies is detected. Also, dependencies on non-existing elements will be ignored. And finally, this rule should only be used with custom templates.

Available for the following controls: checkbox, date, file, password, radio select, text, textarea, time.

  1. // $obj is a reference to a control
  2. $obj->set_rule(array(
  3.  
  4.      // any other rules will be checked only
  5.      // if all of the following conditions are met
  6.      'dependencies'  =>  array(
  7.  
  8.         // the value of the control named "input1" is "Value 1"
  9.         'input1'    =>  'Value 1',
  10.  
  11.         // the value of the control named "input2" is "Value 2" OR "Value 3"
  12.         'input2'    =>  array('Value 2''Value 3'),
  13.  
  14.         // the value of the control named "radio1" is "Option 1" OR "Option 2"
  15.         'radio1'    =>  array('Option 1''Option 2'),
  16.  
  17.         // the value of the control named "checkbox1" (where multiple options can
  18.         // be checked, same as for multiple selects) is
  19.         // 'Option 1' AND 'Option 2'
  20.         //  OR
  21.         // 'Option 4'
  22.         //  OR
  23.         // 'Option 1' AND 'Option 3'
  24.         'checkbox1' =>  array(
  25.                             array('Option 1''Option 2')
  26.                             'Option 4',
  27.                             array('Option 1''Option 3')
  28.                         ),
  29.  
  30.         // the "submit" control having the "btnsubmit" ID is clicked
  31.         'btnsubmit' =>  'click',
  32.  
  33.      ),
  34.  
  35.     // this rule will be checked only
  36.     // if all of the conditions above are met
  37.     'required'      =>  array('error''Value is required!'),
  38. ));

Whenever any of the elements in the "dependencies" rule changes value, the library will check if all the conditions are met and, if a callback function is attached, will execute the callback function. The callback function's first argument will be the boolean result of checking if all the conditions are met. Optionally, additional comma separated arguments may be passed to the callback function (separated with a comma from the function name). Optional arguments can be used for having a single callback function instead of more, and doing different actions depending on the optional argument/arguments

To attach a callback function, declare the "dependencies" rule like this:

  1. // $obj is a reference to a control
  2. $obj->set_rule(array(
  3.  
  4.     // notice an array of arrays...
  5.     'dependencies'  =>  array(array(
  6.  
  7.         // conditions
  8.  
  9.     )'callback_function[, argument]'),
  10.  
  11. ));

Here are some examples of how to define the callback function in JavaScript:

  1. // in the global scope and outside the "domready" event
  2. var my_callback function(valid{
  3.     // all conditions are met
  4.     if (valid{}
  5.     // if not all conditions are met
  6.     else {}
  7. }
  8.  
  9. // ...here comes the rest of your code
  10. $(document).ready(function({});
  11.  
  12. /* ======================================================*/
  13.  
  14. // the same as above, again, outside the "domready" event
  15. function my_callback(valid{
  16.     // all conditions are met
  17.     if (valid{}
  18.     // if not all conditions are met
  19.     else {}
  20. }
  21.  
  22. // ...here comes the rest of your code
  23. $(document).ready(function({});
  24.  
  25. /* ======================================================*/
  26.  
  27. // create a variable in the global scope
  28. var my_callback;
  29.  
  30. // put your function inside the "doready" event
  31. $(document).ready(function({
  32.  
  33.     // but tied to the variable from the global scope...
  34.     my_callback function(valid{
  35.         // all conditions are met
  36.         if (valid{}
  37.         // if not all conditions are met
  38.         else {}
  39.     }
  40.  
  41. });
  42.  
  43. /* ======================================================*/
  44.  
  45. // don't pollute the global scope, use namespaces
  46. $(document).ready(function({
  47.  
  48.     myNameSpace {
  49.         my_callbackfunction(valid{
  50.             // all conditions are met
  51.             if (valid{}
  52.             // if not all conditions are met
  53.             else {}
  54.         }
  55.     }
  56.  
  57. });
  58.  
  59. // in PHP, refer to the callback function like myNameSpace.my_callback
  60. $obj->set_rule(array(
  61.  
  62.     // notice an array of arrays...
  63.      'dependencies'  =>  array(array(
  64.         // conditions
  65.      )'myNameSpace.my_callback'),
  66.  
  67. ));

  • digits
  1. 'digits' => array($additional_characters$error_block$error_message)

where

  • additional_characters is a list of additionally allowed characters besides digits (provide an empty string if none); note that if you want to use / (backslash) you need to specify it as three (3) backslashes ("///")!

  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed
Validates if the value contains only digits (0 to 9) plus characters given as additional characters (if any).

When this rule is set, element's "type" attribute will be automatically changed to "number", making the element more friendly to mobile users

Available for the following controls: password, text, textarea

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'digits' => array(
  4.         '-'                         // allow digits and dash
  5.         'error',                    // variable to add the error message to
  6.         'Only digits are allowed!'  // error message if value doesn't validate
  7.      )
  8. );

  • email
  1. 'email' => array($error_block$error_message)

where

  • error_block is the PHP variable to append the error message to, in case the rule does not validate

  • error_message is the error message to be shown when rule is not obeyed
Validates if the value is a properly formatted email address.

When this rule is set, element's "type" attribute will be automatically changed to "email", making the element more friendly to mobile users

Available for the following controls: password, text, textarea

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'email' => array(
  4.         'error',                    // variable to add the error message to
  5.         'Invalid email address!'    // error message if value doesn't validate
  6.      )
  7. );

  • emails
  1. 'emails' => array($error_block$error_message)

where

  • error_block is the PHP variable to append the error message to, in case the rule does not validate

  • error_message is the error message to be shown when rule is not obeyed
Validates if the value is a properly formatted email address or a comma separated list of properly formatted email addresses.

Available for the following controls: password, text, textarea

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'emails' => array(
  4.         'error',                        // variable to add the error message to
  5.         'Invalid email address(es)!'    // error message if value doesn't validate
  6.      )
  7. );

  • filesize
  1. 'filesize' => array($file_size$error_block$error_message)

where

  • file_size is the allowed file size, in bytes

  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed
Validates if the size (in bytes) of the uploaded file is not larger than the value (in bytes) specified by file_size.

Note that $file_size should be lesser or equal to the value of upload_max_filesize set in php.ini!

Available only for the file control.

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'filesize' => array(
  4.         '102400',                           // maximum allowed file size (in bytes)
  5.         'error',                            // variable to add the error message to
  6.         'File size must not exceed 100Kb!'  // error message if value doesn't validate
  7.      )
  8. );

  • filetype

If you want to check for images use the dedicated "image" rule instead!

  1. 'filetype' => array($file_types$error_block$error_message)

where

  • file_types is a string of comma separated file extensions representing uploadable file types

  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed
Validates only if the uploaded file's MIME type matches the MIME types associated with the extensions set by file_types as defined in mimes.json file.

Note that for PHP versions 5.3.0+, compiled with the "php_fileinfo" extension, the uploaded file's mime type is determined using PHP's finfo_file function; Otherwise, the library relies on information available in the $_FILES super-global for determining an uploaded file's MIME type, which, as it turns out, is determined solely by the file's extension, representing a potential security risk;

Available only for the file control.

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'filetype' => array(
  4.         'xls, xlsx'                 // allow only EXCEL files to be uploaded
  5.         'error',                    // variable to add the error message to
  6.         'Not a valid Excel file!'   // error message if value doesn't validate
  7.      )
  8. );

  • float
  1. 'float' => array($additional_characters$error_block$error_message)

where

  • additional_characters is a list of additionally allowed characters besides digits, one dot and one minus sign (provide an empty string if none); note that if you want to use / (backslash) you need to specify it as three (3) backslashes ("///")!

  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed
Validates if the value contains only digits (0 to 9) and/or one dot (but not as the very first character) and/or one minus sign (but only if it is the very first character) plus characters given as additional characters (if any).

When this rule is set, element's "type" attribute will be automatically changed to "number", making the element more friendly to mobile users

Available for the following controls: password, text, textarea

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'float' => array(
  4.         ''                  // don't allow any extra characters
  5.         'error',            // variable to add the error message to
  6.         'Invalid number!'   // error message if value doesn't validate
  7.      )
  8. );

  • image
  1. 'image' => array($error_block$error_message)

where

  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed

Validates only if the uploaded file is a valid GIF, PNG or JPEG image file.

Available only for the file control.

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'image' => array(
  4.         'error',                                // variable to add the error message to
  5.         'Not a valid GIF, PNG or JPEG file!'    // error message if value doesn't validate
  6.      )
  7. );
  • length
  1. 'length' => array($minimum_length$maximum_length$error_block$error_message$show_counter)

where

  • minimum_length is the minimum number of characters the values should contain
  • maximum_length is the maximum number of characters the values should contain
  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed
  • show_counter if set to TRUE, a counter showing the remaining characters will be displayed along with the element
If you want to change the counter's position, do so by setting margins for the .Zebra_Character_Counter class in the zebra_form.css file

Validates only if the number of characters of the value is between $minimum_length and $maximum_length.

If an exact length is needed, set both $minimum_length and $maximum_length to the same value.

Set $maximum_length to 0 (zero) if no upper limit needs to be set for the value's length.

Available for the following controls: password, text, textarea

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'length' => array(
  4.         3,                                              // minimum length
  5.         6,                                              // maximum length
  6.         'error',                                        // variable to add the error message to
  7.         'Value must have between 3 and 6 characters!'   // error message if value doesn't validate
  8.      )
  9. );

  • number
  1. 'number' => array($additional_characters$error_block$error_message)

where

  • additional_characters is a list of additionally allowed characters besides digits and one minus sign (provide an empty string if none); note that if you want to use / (backslash) you need to specify it as three (3) backslashes ("///")!

  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed
Validates if the value contains only digits (0 to 9) and/or one minus sign (but only if it is the very first character) plus characters given as additional characters (if any).

When this rule is set, element's "type" attribute will be automatically changed to "number", making the element more friendly to mobile users

Available for the following controls: password, text, textarea

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'number' => array(
  4.         ''                  // don't allow any extra characters
  5.         'error',            // variable to add the error message to
  6.         'Invalid integer!'  // error message if value doesn't validate
  7.      )
  8. );

  • range
  1. 'range' => array($range$error_block$error_message)

where

  • range is an array with 2 values, representing the minimum and maximum allowed values. 0 (zero) means "any value". Therefore, a range of array(100, 0) would validate values of 100 and above, array(50, 100) would validate values between 50 and 100 (inclusive), while (0, 50) would validate values below 51

  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed
Validates if the value is within range

Available for the following controls: text

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'range' => array(
  4.         array(50100)                                                  // allow values between 50 and 100 (inclusive)
  5.         'error',                                                        // variable to add the error message to
  6.         'The entered value must be between 50 and 100 (inclusive)'      // error message if value doesn't validate
  7.      )
  8. );

  • regexp
  1. 'regexp' => array($regular_expression$error_block$error_message)

where

  • regular_expression is the regular expression pattern (without delimiters) to be tested on the value

  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed
Validates if the value satisfies the given regular expression

Available for the following controls: password, text, textarea

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'regexp' => array(
  4.         '^0123'                         // the regular expression
  5.         'error',                        // variable to add the error message to
  6.         'Value must begin with "0123"'  // error message if value doesn't validate
  7.      )
  8. );

  • required
  1. 'required' => array($error_block$error_message)

where

  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed

Validates only if a value exists.

Available for the following controls: checkbox, date, file, password, radio, select, text, textarea, time

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'required' => array(
  4.         'error',            // variable to add the error message to
  5.         'Field is required' // error message if value doesn't validate
  6.      )
  7. );

  • resize
This rule requires the prior inclusion of the Zebra_Image library!

  1. 'resize' => array(
  2.     $prefix,
  3.     $width,
  4.     $height,
  5.     $preserve_aspect_ratio,
  6.     $method,
  7.     $background_color,
  8.     $enlarge_smaller_images,
  9.     $jpeg_quality,
  10.     $error_block,
  11.     $error_message,
  12. )

where

  • prefix: If the resized image is to be saved as a new file and the originally uploaded file needs to be preserved, specify a prefix to be used for the new file. This way, the resized image will have the same name as the original file but prefixed with the given value (i.e. "thumb_").

Specifying an empty string as argument will instruct the script to apply the resizing to the uploaded image and therefore overwriting the originally uploaded file.

  • width is the width to resize the image to.

If set to 0, the width will be automatically adjusted, depending on the value of the height argument so that the image preserves its aspect ratio.

If preserve_aspect_ratio is set to TRUE and both this and the height arguments are values greater than 0, the image will be resized to the exact required width and height and the aspect ratio will be preserved (see the description for the method argument below on how can this be done).

If preserve_aspect_ratio is set to FALSE, the image will be resized to the required width and the aspect ratio will be ignored.

If both width and height are set to 0, a copy of the source image will be created (jpeg_quality will still apply).

If either width or height are set to 0, the script will consider the value of the preserve_aspect_ratio to bet set to TRUE regardless of its actual value!

  • height is the height to resize the image to.

If set to 0, the height will be automatically adjusted, depending on the value of the width argument so that the image preserves its aspect ratio.

If preserve_aspect_ratio is set to TRUE and both this and the width arguments are values greater than 0, the image will be resized to the exact required width and height and the aspect ratio will be preserved (see the description for the method argument below on how can this be done).

If preserve_aspect_ratio is set to FALSE, the image will be resized to the required height and the aspect ratio will be ignored.

If both height and width are set to 0, a copy of the source image will be created (jpeg_quality will still apply).

If either height or width are set to 0, the script will consider the value of the preserve_aspect_ratio to bet set to TRUE regardless of its actual value!

  • preserve_aspect_ratio: If set to TRUE, the image will be resized to the given width and height and the aspect ratio will be preserved.

Set this to FALSE if you want the image forcefully resized to the exact dimensions given by width and height ignoring the aspect ratio

  • method: is the method to use when resizing images to exact width and height while preserving aspect ratio.

If the preserve_aspect_ratio property is set to TRUE and both the width and height arguments are values greater than 0, the image will be resized to the exact given width and height and the aspect ratio will be preserved by using on of the following methods:

  • ZEBRA_IMAGE_BOXED - the image will be scalled so that it will fit in a box with the given width and height (both width/height will be smaller or equal to the required width/height) and then it will be centered both horizontally and vertically. The blank area will be filled with the color specified by the background_color argument. (the blank area will be filled only if the image is not transparent!)
  • ZEBRA_IMAGE_NOT_BOXED - the image will be scalled so that it could fit in a box with the given width and height but will not be enclosed in a box with given width and height. The new width/height will be both smaller or equal to the required width/height

  • ZEBRA_IMAGE_CROP_TOPLEFT
  • ZEBRA_IMAGE_CROP_TOPCENTER
  • ZEBRA_IMAGE_CROP_TOPRIGHT
  • ZEBRA_IMAGE_CROP_MIDDLELEFT
  • ZEBRA_IMAGE_CROP_CENTER
  • ZEBRA_IMAGE_CROP_MIDDLERIGHT
  • ZEBRA_IMAGE_CROP_BOTTOMLEFT
  • ZEBRA_IMAGE_CROP_BOTTOMCENTER
  • ZEBRA_IMAGE_CROP_BOTTOMRIGHT
For the methods involving crop, first the image is scaled so that both its sides are equal or greater than the respective sizes of the bounding box; next, a region of required width and height will be cropped from indicated region of the resulted image.

  • background_color is the hexadecimal color of the blank area (without the #). See the method argument.
  • enlarge_smaller_images: if set to FALSE, images having both width and height smaller than the required width and height, will be left untouched (jpeg_quality will still apply).

  • jpeg_quality indicates the quality of the output image (better quality means bigger file size).
Range is 0 - 100

Available only for JPEG files.

  • error_block is the PHP variable to append the error message to, in case the rule does not validate

  • error_message is the error message to be shown when rule is not obeyed
This rule must come after the upload rule!

This is not an actual "rule", but because it can generate an error message it is included here.

Available only for the file control

This rule is not available client-side!

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'resize' => array(
  4.         'thumb_',                           // prefix
  5.         '150',                              // width
  6.         '150',                              // height
  7.         true,                               // preserve aspect ratio
  8.         ZEBRA_IMAGE_BOXED,                  // method to be used
  9.         'FFFFFF',                           // background color
  10.         true,                               // enlarge smaller images
  11.         85,                                 // jpeg quality
  12.         'error',                            // variable to add the error message to
  13.         'Thumbnail could not be created!'   // error message if value doesn't validate
  14.      )
  15. );
  16.  
  17. // for multiple resizes, use an array of arrays:
  18. $obj->set_rule(
  19.      'resize' => array(
  20.         array('thumb1_'150150trueZEBRA_IMAGE_BOXED'FFFFFF'true85'error''Error!'),
  21.         array('thumb2_'300300trueZEBRA_IMAGE_BOXED'FFFFFF'true85'error''Error!'),
  22.      )
  23. );

  • upload
  1. 'upload' => array($upload_path$file_name$error_block$error_message)

where

  • upload_path the path where to upload the file to, relative to the currently running script.
  • file_name: specifies whether the uploaded file's original name should be preserved, should it be prefixed with a string, or should it be randomly generated.

Possible values can be TRUE: the uploaded file's original name will be preserved; FALSE (or, for better code readability, you should use the "ZEBRA_FORM_UPLOAD_RANDOM_NAMES" constant instead of "FALSE") : the uploaded file will have a randomly generated name; a string: the uploaded file's original name will be preserved but it will be prefixed with the given string (i.e. "original_", or "tmp_").

Note that when set to TRUE or a string, a suffix of "_n" (where n is an integer) will be appended to the file name if a file with the same name already exists at the given path.

  • error_block is the PHP variable to append the error message to, in case the rule does not validate

  • error_message is the error message to be shown when rule is not obeyed
Validates if the file was successfully uploaded to the folder specified by upload_path.

Remember to check the form's $file_upload property for information about the uploaded file after the form is submitted!

Remember to check the form's $file_upload_permissions property for how to set the filesystem permissions of the uploaded files!

Note that once this rule is run client-side, the DOM element the rule is attached to, will get a data-attribute called file_info which will contain information about the uploaded file, accessible via JavaScript.

  1. console.log($('#element_id').data('file_info'))

This is not actually a "rule", but because it can generate an error message it is included here

You should use this rule in conjunction with the filesize rule

Available only for the file control

This rule is not available client-side!

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'upload' => array(
  4.         'tmp',                              // path to upload file to
  5.         ZEBRA_FORM_UPLOAD_RANDOM_NAMES,     // upload file with random-generated name
  6.         'error',                            // variable to add the error message to
  7.         'File could not be uploaded!'       // error message if value doesn't validate
  8.      )
  9. );

  • url
  1. 'url' => array($require_protocol$error_block$error_message)

where

  • require_protocol indicates whether the http or https prefix should be mandatory or not

  • error_block is the PHP variable to append the error message to, in case the rule does not validate
  • error_message is the error message to be shown when rule is not obeyed
Validates if the value represents a valid URL

The regular expression used is the following:

  1. /^(http(s)?\:\/\/)?[^\s\.]+\..{2,}/i

Some example URLs that are considered valid by this rule are:

  • google.com (if the require_protocol attribut is set to FALSE)
  • http://google.com
  • http://www.google.com
  • http://www.google.com?foo=bar
  • http://www.google.com?foo=bar#anchor
Note that this rule will only validate common URLs and does not attempt to be a validator for all possible valid URLs, and therefore it will fail on most of the more exotic URLs used in the tests here. Keep that in mind when deciding on whether to use this rule or not. Nevertheless, this should be enough for validating most of the URLs you encountered on a daily basis.

Available for the following controls: password, text, textarea

  1. // $obj is a reference to a control
  2. $obj->set_rule(
  3.      'url' => array(
  4.         true,               // require users to start the URL with http:// or https:// in order for the URL to be valid
  5.         'error',            // variable to add the error message to
  6.         'Not a valid URL!'  // error message if value doesn't validate
  7.      )
  8. );
Parameters:
array $rules

An associative array

See above how it needs to be specified for each rule

Top

method _render_attributes()

string _render_attributes ( )

Converts the array with control's attributes to valid HTML markup interpreted by the toHTML() method

Note that this method skips $private_attributes

Tags:
return: Returns a string with the control's attributes
access: protected
Top