Fork me on GitHub

Validation

Basics

In Hathoora PHP Framework validation is not coupled with forms or data models. Validation is a stand-alone process that can be used for anything.

hathoora\form\validation is the main validation class. In order to use validation, an array defining validation parameters is required. There are three main paramerts for validation:

  • required - boolean value - when true, an empty value will fail validation.
  • filters - array of filters/methods that must be applied (in order defined) to the value before validation.
  • rules - array of rules that must be matched (in order defined) against the given value.

Below is an example of validation rules for a valid blog post:

        
            $arrValidations = array(
                ...
                'title' => array(
                    'required' => true,
                    'rules' => array(
                        array(
                            'minlength' => 3,
                            'maxlength' => 100,
                            'message' => 'Title must be 3-100 characters long',
                        ),
                    )
                ),
                'tags' => array(
                    'rules' => array(
                        array(
                            'maxlength' => 255,
                            'callback' => array(&$this, 'validateRuleTags'),
                            'message' => 'Too many tags.',
                        ),
                    )
                ),
                'slug' => array(
                    'filters' => array(
                        'contentImage' => array(&$this, 'filterSlug'),
                    ),
                )
                ...
            );
        
    

In above example we are trying to validate the following fields:

  • title
  • tags
  • slug

In order to validate use validation::validate($arrValidations, &$arrValues). Where $arrValues must be an associate array containing fields we are validating against.

        
            $arrValidations = array(
                ...
            );
            $arrValues = array(
                'title' => 'Hello World',
                'tags' => 'Hello, World',
                'slug' => 'Hello World',
            );

            $mixedResult = validation::validate($arrValidations, &$arrValues);
        
    

Validation Result - validation::validate($arrValidations, &$arrValues) returns the following results:

  • TRUE when validation passed
  • Associative Array of error messages where key is the field being validated.

Values Array By Referrence - the array of values we are trying to validate must be passed as a referrence because of trimming and filters.


Triming - by detault array of values will be trimmed. If you want to disable trimming, then use:

        
            $arrValidations = array(
                ...
            );
            $arrValues = array(
                ...
            )

            $mixedResult = validation::validate($arrValidations, &$arrValues, $trimming = false);
        
    

Translations - you can use translations service to translate rule messages like following:

        
            $arrValidations = array(
                'title' => array(
                    'required' => true,
                    'rules' => array(
                        array(
                            'minlength' => 3,
                            'maxlength' => 100,
                            'message' => 'title_form_error',
                        ),
                    )
            );
            $arrValues = array(
                ...
            )

            $mixedResult = validation::validate($arrValidations, &$arrValues, $trimming = false, $translation = true);
        
    

In above example title_form_error will be translated accordingly. You can also use dynamic {{field}} inside translations.


Default Validation Messages are used in the following scenarios:

  • validation_field_value_empty when a field is required but has no value
  • validation_field_general_error validation rule failed, but there is no message specified for it.
  • validation_empty_form_submitted_error all values to be validated are empty/nonexistent.

If you have translation enabled then above would be translated accordingly. If you are not using translations then you can define these messages inside application configurations like so:

        
            # File HATHOORA_ROOTPATH/app/directory/namespace/config/config_HATHOORA_ENV.yml

            hathoora:
                validation:
                    messages:
                        validation_field_value_empty: 'Field is required.'
                        validation_field_general_error: 'Please enter a value.'
                        validation_empty_form_submitted_error: 'Make sure you have submitted the form correctly.'

        
    

Filters

Filters allows you to apply a series of filter to a field's value before it is being validated. See the examples below:

        
            # Validation
            $arrValidations = array(
                ...
                'slug' => array(
                    ...
                    'filters' => array(
                        'slugify' => array(&$this, 'filterSlug'),
                    )
                    ...
                ),
                'title' => array(
                    ...
                    'filters' => array(
                        // basically pass anything that you would to call_user_func_array()
                        'prefix' => array(__NAMESPACE__, 'staticPrefixFunction'),
                        'suffix' => array(__NAMESPACE__, 'staticSuffixFunction')
                    )
                    ...
                )
                ...
            );



            # Fields to be validated against
            $arrValues = array(
                'title' => 'This is a title',
                'slug' => 'Hello World',
            );



            # Filter functions
            /**
             * $value is the value of field
             * $arrValues is the array of all values
             */
            public function filterSlug($value, &$arrValues)
            {
                // $arrValues['slug'] would become 'hello-world'
                return \hathoora\helper\stringHelper::slugify($value);
            }

            /**
             * $value is the value of field
             * $arrValues is the array of all values
             */
            public static function staticPrefixFunction($value, &$arrValues)
            {
                // $arrValues['title'] would become 'PREFIX This is a title'
                return 'PREFIX ' . $value;
            }

            /**
             * $value is the value of field
             * $arrValues is the array of all values
             */
            public static function staticSuffixFunction($value, &$arrValues)
            {
                // $arrValues['title'] would become 'PREFIX This is a title SUFFIX'
                return $value . ' SUFFIX';
            }

            $mixedResult = validation::validate($arrValidations, &$arrValues);
        
    

Whether validation passes or not, at the end of above validation, $arrValues would be transformed into:

        
            $arrValues = array(
                'title' => 'PREFIX This is a title SUFFIX',
                'slug' => 'hello-world',
            );
        
    

Rules

You can apply a series of validation rules for a field to be checked against. These rules are matched in the order specified and would stop (per field basis) when a rule is not validated.

Following are builtin rules that Hathoora PHP Framework ships with:

  • minlength
  • maxlength
  • url
  • email
  • min
  • max
  • numeric
  • alpha
  • regex
  • noHtml
  • notTheseHtmlTags
  • callback

Rules are demonstrated in the following sample code.

        
            $arrValidations = array(
                ...
                '...' => array(
                    ...
                    'rules' => array(
                        array(
                            'minlength' => 3,
                            'maxlength' => 100,

                            # must be a valid URL
                            'url' => true,

                            # must be a valid URL
                            'email' => true,

                            # minimum value to be 3
                            'min' => 3,

                            # maximum value to be 10
                            'minlength' => 10,

                            'numeric' => true,
                            'alpha' => true,

                            # valid when passes the following regex
                            'regex' => '^[a-z0-9]{3,}$',

                            # field cannot have HTML
                            'noHtml' => true,

                            # or following tags are valid, any other tag would fail validation
                            'noHtml' => 'a,i,b',

                            # field validation when following fields are present
                            'notTheseHtmlTags' => 'javascript, iframe',

                            # custom validation (call_user_func_array() syntax)
                            'callback' => 'callback' => array($this, 'validateRuleXYZ'),
                        )
                    )
                )
            );


            /**
             * Sample callback validation rule
             */
            public function validateRuleXYZ($value, &$arrForm)
            {
                ... some validation ...
                if (noErrors)
                    return true;
                else
                    return 'String of error message';
            }
        
    

Validation For ModelSAR Class

If you are using a ModelSAR class, then same rules apply at above, however you have the convineance of passing an object instead of array of values.

        

            $post = new Post();
            $post->title = 'Some title';

            $arrValidations = array(
                ...
                'title' => array(
                    'required' => true,
                    'rules' => array(
                        array(
                            'minlength' => 3,
                            'maxlength' => 100,
                            'callback' => array(&$post, 'validateField'),
                            'message' => 'Title must be 3-100 characters long',
                        ),
                    )
                )
                ...
            );

            return validation::validate($arrValidations, $post);
        
    
Page Took:         6.52 msec
Page Memory:   538.7k
docs / viewController / view (200)
Request UUID: 59963c13a78590.58703564
Get
Post
Cookies
Files
Session
Server
Response
No data.
No data.
No data.
No data.
No data.
REDIRECT_HATHOORA_ENV
prod
REDIRECT_STATUS
200
HATHOORA_ENV
prod
HTTP_HOST
hathoora.org
HTTP_X_FORWARDED_FOR
54.224.184.251
HTTP_X_REAL_IP
54.224.184.251
HTTP_CONNECTION
close
HTTP_ACCEPT_ENCODING
x-gzip, gzip, deflate
HTTP_USER_AGENT
CCBot/2.0 (http://commoncrawl.org/faq/)
HTTP_ACCEPT
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
PATH
/sbin:/usr/sbin:/bin:/usr/bin
SERVER_SIGNATURE
Apache/2.2.15 (CentOS) Server at hathoora.org Port 80
SERVER_SOFTWARE
Apache/2.2.15 (CentOS)
SERVER_NAME
hathoora.org
SERVER_ADDR
192.168.1.11
SERVER_PORT
80
REMOTE_ADDR
207.126.164.119
DOCUMENT_ROOT
/var/websites/hathoora.org/docroot
SERVER_ADMIN
webmaster@hathoora.org
SCRIPT_FILENAME
/var/websites/hathoora.org/docroot/index.php
REMOTE_PORT
46068
REDIRECT_URL
/docs/v1/validation
GATEWAY_INTERFACE
CGI/1.1
SERVER_PROTOCOL
HTTP/1.0
REQUEST_METHOD
GET
QUERY_STRING
REQUEST_URI
/docs/v1/validation
SCRIPT_NAME
/index.php
PHP_SELF
/index.php
REQUEST_TIME_FLOAT
1503018003.685
REQUEST_TIME
1503018003
Status: 200
Headers:
Content-Type
text/html; charset=UTF-8
Configutation
Key Value
app.admin
Array
(
    [pattern] => /admin(|/)
    [directory] => hathoora
    [namespace] => hathoora\admin
)
app.docs
Array
(
    [pattern] => /docs(|/)
    [directory] => hathoora
    [dispatcher] => Array
        (
            [class] => customDispatcher
            [method] => dispatch
        )

)
app.site
Array
(
    [default] => 1
)
hathoora.logger
Array
(
    [profiling] => Array
        (
            [enabled] => 1
        )

    [logging] => Array
        (
            [enabled] => 1
            [level] => DEBUG
        )

    [webprofiler] => Array
        (
            [enabled] => 1
            [system] => 
            [show_redirects] => 
        )

)
hathoora.template
Array
(
    [engine] => Array
        (
            [name] => Stuob
        )

)
hathoora.database
Array
(
    [default] => mysql://dbuser:dbpassword@dbhost:3306/dbname
)
services.container
Array
(
    [class] => \hathoora\container
    [method] => getContainer
)
Logging (14)
hathoora.logger.logging.enabled: 1
# Time (msec) Level Memory (KB) Message
1 2.322 DEBUG 309.31 Configuration loaded:
Array
(
    [0] => app_prod.yml
    [1] => config_prod.yml
)
2 2.608 DEBUG 322.92 Listener "kernel.terminate[webprofiler]" has been added because of hathoora.logger.webprofiler.enabled
3 2.774 DEBUG 326.31 Event kernel.ready has been registered.
4 2.981 DEBUG 334.68 Calling App dispatcher (Array ( [class] => customDispatcher [method] => dispatch ) )...
5 3.142 DEBUG 348.99 Event kernel.route has been registered.
6 3.427 DEBUG 378.34 Event kernel.controller has been registered.
7 3.480 DEBUG 379.28 Calling controller (\docs\controller\viewController::view) with following params
Array
(
    [0] => v1
    [1] => validation
)
8 4.096 INFO 466.64 Template (docs/v1/validation.tpl.php) loaded
9 4.320 INFO 499.78 Template (/var/websites/hathoora.org/app/hathoora/docs//resources/templates/components/htmlMeta.tpl.php) loaded
10 4.555 INFO 501.03 Template (/var/websites/hathoora.org/app/hathoora/docs//resources/templates/components/flashMessages.tpl.php) loaded
11 6.112 INFO 445.89 Template (docs.tpl.php) fetched.
12 6.175 DEBUG 445.48 Event kernel.response has been registered.
13 6.218 DEBUG 446.67 Event kernel.terminate has been registered.
14 6.332 DEBUG 449.89 Event kernel.terminate->webprofiler has been notified.
Profiling
template
# Time (msec) Name Cached Took (msec)
1 3.587 docs.tpl.php 0 2.395