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    
Last Updated Ratings Unique User Downloads Download Rankings
2022-08-13 (2 days ago) RSS 2.0 feedNot yet rated by the usersTotal: 44 This week: 13All time: 10,390 This week: 21Up
Version License PHP version Categories
formal 1.1.1Artistic 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
Nominee
Vote
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. is available for providing paid consulting. Contact Nikos M. .
Classes: 17 packages by
Country: Greece Greece
Age: 45
All time rank: 9359 in Greece Greece
Week rank: 1 Up
Innovation award
Innovation award
Nominee: 7x

Winner: 1x

Details

Formal

A simple and versatile (form) input data validation framework based on built-in and custom rules for PHP, JavaScript, Python

version 1.1.1

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 & 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 & 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', $minValue);

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

// clamp typecaster
Formal::typecast('clamp', [$minValue, $maxValue]);

// 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', $maxCount);

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

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

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

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

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

// 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, ..]);

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

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

// 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:44
This week:13
All time:10,390
This week:21Up
For more information send a message to info at phpclasses dot org.