PHP Classes

Formal PHP Validation Library: Validate a set values with support to type casting

Recommend this page to a friend!
  Info   View files Example   View files View files (18)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog (1)    
Last Updated Ratings Unique User Downloads Download Rankings
2024-05-17 (Yesterday) RSS 2.0 feedNot enough user ratingsTotal: 93 This week: 6All time: 9,887 This week: 16Up
Version License PHP version Categories
formal 1.3.0Artistic License5PHP 5, Data types, Validation
Description 

Author

This package can validate a set of values with support to typecasting.

It can define a set of validation rules with configurable parameters.

The package can also define type casting rules that can combine several types of validation rules.

It can process a set of values passed as an array and returns the validation rules and a list of validation errors.

This package also implements this validation library in JavaScript and Python.

Innovation Award
PHP Programming Innovation award nominee
July 2022
Number 3
Many Web applications need to validate values entered by the users to avoid invalid values that can make the application work unexpectedly.

Usually, developers define a set of rules to validate values entered by users. In some cases, specific values need to be validate by several rules.

This package supports the concept of type casting. This concept allows the definition of rules that combine several other rules into a single rule.

This way, developers can simplify the definition of complex rules in less code than if they had to define all simple rules for each value that their applications need to validate.

Manuel Lemos
Picture of Nikos M.
Name: Nikos M. <contact>
Classes: 18 packages by
Country: Greece Greece
Innovation award
Innovation award
Nominee: 7x

Winner: 2x

Example

<?php

define
('ROOT', dirname(__FILE__));
include(
ROOT.'/../../tico/tico/Tico.php');

tico('http://localhost:8000', ROOT)
    ->
option('webroot', ROOT)
    ->
option('views', [tico()->path('/views')])
    ->
option('case_insensitive_uris', true)
    ->
set('formal', function() {
        include(
ROOT.'/../src/php/Formal.php');
        return (new
Formal())
            ->
option('WILDCARD', '*') // default
           
->option('SEPARATOR', '.') // default
           
->option('break_on_first_error', false) // default
       
;
    })
    ->
on('*', '/', function() {

       
$err = array();
       
$data = array();
        if (
'POST' === tico()->requestMethod())
        {
           
$data = tico()->get('formal')
                ->
option('defaults', [
                   
'foo' => 'bar',
                   
'moo.*.foo' => 'bar',
                   
'koo.*' => 'bar'
               
])
                ->
option('typecasters', [
                   
'num.*' => Formal::typecast('composite', [Formal::typecast('float'), Formal::typecast('clamp', [0.0, 1.0])
                ])])
                ->
option('validators', [
                   
'date.*' => Formal::validate('match', Formal::datetime('Y-m-d'), '"{key}" should match {args} !'),
                   
'date.0' => Formal::validate('eq', Formal::field('date.1'))
                ])
                ->
process(tico()->request()->request->all())
            ;
           
$err = tico()->get('formal')->getErrors();
        }
       
tico()->output(
            array(
               
'title' => 'Index',
               
'data' => $data,
               
'err' => $err
           
),
           
'index.tpl.php'
       
);

    })
    ->
on(false, function() {

       
tico()->output(
            array(),
           
'404.tpl.php',
            array(
'StatusCode' => 404)
        );

    })
    ->
serve()
;

exit;


Details

Formal

A simple and versatile (Form) Data validation framework based on Rules for PHP, JavaScript, Python

version 1.3.0

Formal

see also:

  • ModelView a simple, fast, powerful and flexible MVVM framework for JavaScript
  • tico a tiny, super-simple MVC framework for PHP
  • LoginManager a simple, barebones agnostic login manager for PHP, JavaScript, Python
  • SimpleCaptcha a simple, image-based, mathematical captcha with increasing levels of difficulty for PHP, JavaScript, Python
  • Dromeo a flexible, and powerful agnostic router for PHP, JavaScript, Python
  • PublishSubscribe a simple and flexible publish-subscribe pattern implementation for PHP, JavaScript, Python
  • Importer simple class &amp; dependency manager and loader for PHP, JavaScript, Python
  • Contemplate a fast and versatile isomorphic template engine for PHP, JavaScript, Python
  • HtmlWidget html widgets, made as simple as possible, both client and server, both desktop and mobile, can be used as (template) plugins and/or standalone for PHP, JavaScript, Python (can be used as plugins for Contemplate)
  • Paginator simple and flexible pagination controls generator for PHP, JavaScript, Python
  • Formal a simple and versatile (Form) Data validation framework based on Rules for PHP, JavaScript, Python
  • Dialect a cross-vendor &amp; cross-platform SQL Query Builder, based on GrammarTemplate, for PHP, JavaScript, Python
  • DialectORM an Object-Relational-Mapper (ORM) and Object-Document-Mapper (ODM), based on Dialect, for PHP, JavaScript, Python
  • Unicache a simple and flexible agnostic caching framework, supporting various platforms, for PHP, JavaScript, Python
  • Xpresion a simple and flexible eXpression parser engine (with custom functions and variables support), based on GrammarTemplate, for PHP, JavaScript, Python
  • Regex Analyzer/Composer Regular Expression Analyzer and Composer for PHP, JavaScript, Python

Contents

  1. Example
  2. API Reference

Example

<form method="post">
Foo: <input name="foo" type="text" value="" />

Moo:
<input name="moo[0][choo]" type="text" value="1" />
<input name="moo[1][choo]" type="text" value="2" />
<input name="moo[2][choo]" type="text" value="3" />

Koo:
<input name="koo[]" type="text" value="" />
<input name="koo[]" type="text" value="" />
<input name="koo[]" type="text" value="" />

Nums:
<input name="num[]" type="text" value="0.1" />
<input name="num[]" type="text" value="1.2" />

Dates:
<input name="date[]" type="text" value="2012-11-02" />
<input name="date[]" type="text" value="20-11-02" />

<button type="submit">Submit</button>
</form>

$formal = (new Formal())
        ->option('WILDCARD', '*') // default
        ->option('SEPARATOR', '.') // default
        ->option('break_on_first_error', false) // default
        ->option('defaults', [
            'foo' => 'bar',
            'moo.*.foo' => 'bar',
            'koo.*' => 'bar'
        ])
        ->option('typecasters', [
            'num.*' => Formal::typecast('composite', [Formal::typecast('float'), Formal::typecast('clamp', [0.0, 1.0])])
        ])
        ->option('validators', [
            'date.*' => Formal::validate('match', Formal::datetime('Y-m-d'), '"{key}" should match {args} !'),
            'date.0' => Formal::validate('eq', Formal::field('date.1'))
        ])
;
$data = $formal->process($_POST);
$err = $formal->getErrors();

print_r($data);

echo implode("\n", $err) . PHP_EOL;

echo $err[0]->getMsg() . PHP_EOL;
echo implode('.', $err[0]->getKey()) . PHP_EOL;

/* output

Array
(
    [foo] => bar
    [moo] => Array
        (
            [0] => Array
                (
                    [choo] => 1
                    [foo] => bar
                )

            [1] => Array
                (
                    [choo] => 2
                    [foo] => bar
                )

            [2] => Array
                (
                    [choo] => 3
                    [foo] => bar
                )

        )

    [koo] => Array
        (
            [0] => bar
            [1] => bar
            [2] => bar
        )

    [num] => Array
        (
            [0] => 0.1
            [1] => 1
        )

    [date] => Array
        (
            [0] => 2012-11-02
            [1] => 20-11-02
        )

)
"date.1" should match Y-m-d !
"date.0" must be equal to "date.1"!

"date.1" should match Y-m-d !
date.1
*/

API Reference

Typecasters

// composite typecaster
Formal::typecast('composite', [$typecaster1, $typecaster2/, ../]);

// boolean typecaster
Formal::typecast('bool');

// int typecaster
Formal::typecast('int');

// float typecaster
Formal::typecast('float');

// string typecaster
Formal::typecast('str');

// min value typecaster
Formal::typecast('min', $minValueOrField);

// max value typecaster
Formal::typecast('max', $maxValueOrField);

// clamp typecaster
Formal::typecast('clamp', [$minValueOrField, $maxValueOrField]);

// trim typecaster
Formal::typecast('trim');

// lowercase typecaster
Formal::typecast('lower');

// uppercase typecaster
Formal::typecast('upper');

// custom typecaster
Formal::typecast(function($val, $args, $key, $formalInstance) {
    // typecast and return new $val
    return $val;
}, $args = null);

Validators

// optional validator, only if value is not missing
Formal::validate('optional', $requiredValidator);

// required validator, fails if value is missing or null
Formal::validate('required');

// is numeric validator
Formal::validate('numeric');

// is object validator
Formal::validate('object');

// is array validator
Formal::validate('array';

// is file validator
Formal::validate('file');

// is empty validator
Formal::validate('empty');

// max items validator
Formal::validate('maxitems', $maxCountOrField);

// min items validator
Formal::validate('minitems', $minCountOrField);

// max chars validator
Formal::validate('maxchars', $maxLenOrField);

// min chars validator
Formal::validate('minchars', $minLenOrField);

// max file size validator
Formal::validate('maxsize', $maxSizeOrField);

// min file size validator
Formal::validate('minsize', $minSizeOrField);

// equals validator
Formal::validate('eq', $otherValueOrField);

// not equals validator
Formal::validate('neq', $otherValueOrField);

// greater than validator
Formal::validate('gt', $otherValueOrField);

// greater than or equal validator
Formal::validate('gte', $otherValueOrField);

// less than validator
Formal::validate('lt', $otherValueOrField);

// less than or equal validator
Formal::validate('lte', $otherValueOrField);

// between values (included) validator
Formal::validate('between', [$minValueOrField, $maxValueOrField]);

// in array of values validator
Formal::validate('in', [$val1, $val2/, ../]/or field/);

// not in array of values validator
Formal::validate('not_in', [$val1, $val2/, ../]/or field/);

// match pattern validator
Formal::validate('match', $patternOrField);

// match valid email pattern validator
Formal::validate('email');

// match valid url pattern validator
Formal::validate('url');

// not validator
$validator->_not_($errMsg = null);

// $validator1 and $validator2
$validator1->_and_($validator2);

// $validator1 or $validator2
$validator1->_or_($validator2);

// custom validator
Formal::validate(function($val, $args, $key, $formalInstance, $missingValue, $errMsg) {
    // validate and return true or false
    // optionally you can throw FormalException with custom error message
    throw new FormalException('my custom error message');
    return false;
}, $args = null, $errMsg = null);


  Files folder image Files  
File Role Description
Files folder imagedemo (2 files, 1 directory)
Files folder imagesrc (3 directories)
Files folder imagetest (3 directories)
Accessible without login Image file formal.jpg Icon Icon image
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files  /  demo  
File Role Description
Files folder imageviews (3 files, 1 directory)
  Accessible without login Plain text file index.php Example Example script
  Accessible without login Plain text file server.php Aux. Auxiliary script

  Files folder image Files  /  demo  /  views  
File Role Description
Files folder imagelayout (1 file)
  Accessible without login Plain text file 404.tpl.php Example Example script
  Accessible without login Plain text file content.tpl.php Example Example script
  Accessible without login Plain text file index.tpl.php Example Example script

  Files folder image Files  /  demo  /  views  /  layout  
File Role Description
  Accessible without login Plain text file base.tpl.php Example Example script

  Files folder image Files  /  src  
File Role Description
Files folder imagejs (1 file)
Files folder imagephp (1 file)
Files folder imagepython (2 files)

  Files folder image Files  /  src  /  js  
File Role Description
  Accessible without login Plain text file Formal.js Data Auxiliary data

  Files folder image Files  /  src  /  php  
File Role Description
  Plain text file Formal.php Class Class source

  Files folder image Files  /  src  /  python  
File Role Description
  Accessible without login Plain text file Formal.py Data Auxiliary data
  Accessible without login Plain text file __init__.py Data Auxiliary data

  Files folder image Files  /  test  
File Role Description
Files folder imagejs (2 files)
Files folder imagephp (2 files)
Files folder imagepython (2 files)

  Files folder image Files  /  test  /  js  
File Role Description
  Accessible without login Plain text file out.txt Doc. Documentation
  Accessible without login Plain text file test.js Data Auxiliary data

  Files folder image Files  /  test  /  php  
File Role Description
  Accessible without login Plain text file out.txt Doc. Documentation
  Accessible without login Plain text file test.php Example Example script

  Files folder image Files  /  test  /  python  
File Role Description
  Accessible without login Plain text file out.txt Doc. Documentation
  Accessible without login Plain text file test.py Data Auxiliary data

 Version Control Unique User Downloads Download Rankings  
 100%
Total:93
This week:6
All time:9,887
This week:16Up