, (*1)
Description
HtmlFormValidator is a very easy to use PHP library that will help you
to validate your <form>
data and you can use this independent from your framework of choice., (*2)
Install via "composer require"
composer require voku/html-form-validator
How does this work?
-
First you need to generate a html form, that's completely your part. You can write it manually or you can generate with a framework or a library, it doesn't matter., (*3)
-
Then we use DOM Parsing via voku/simple_html_dom, to detect the current validator and filter rules directly from the html., (*4)
-
And finally, we use Respect/Validation to validate the form., (*5)
Simple Example
use voku\HtmlFormValidator\Validator;
require_once 'composer/autoload.php';
$html = '
';
$rules = $formValidator->getAllRules();
static::assertSame(
[
'music' => [
'top5' => 'in(' . \serialize(['Heino','Michael Jackson','Tom Waits','Nina Hagen','Marianne Rosenberg',]) . ')',
],
],
$rules
);
// --- valid
// fake some data
$_POST = [
'top5' => 'Heino',
];
$formValidatorResult = $formValidator->validate($_POST);
static::assertSame([], $formValidatorResult->getErrorMessages());
// --- invalid
// fake some data
$_POST = [
'top5' => 'fooooo',
];
$formValidatorResult = $formValidator->validate($_POST);
static::assertSame(
[
'top5' => [
'"fooooo" must be in { "Heino", "Michael Jackson", "Tom Waits", "Nina Hagen", "Marianne Rosenberg" }',
],
],
$formValidatorResult->getErrorMessages()
);
Extended Example
use voku\HtmlFormValidator\Validator;
require_once 'composer/autoload.php';
$html = '
';
$formValidator = new Validator($html);
// fake some data
$_POST = [
'user' => [
'email' => 'foo@isanemail',
'name' => 'bar',
],
];
// validate the form
$formValidatorResult = $formValidator->validate($_POST);
// check the result
static::assertFalse($formValidatorResult->isSuccess());
// get the error messages
static::assertSame(
[
'user[email]' => ['Your email [foo@isanemail] address is not correct.'],
'user[date]' => [
'Date is not correct.',
'Date is empty.',
],
],
$formValidatorResult->getErrorMessages()
);
// get the new html
static::assertSame(
'
',
$formValidatorResult->getHtml()
);
Validator
You can use all validators from here., (*6)
e.g.: data-validator="date"
|| data-validator="' . \Respect\Validation\Rules\Date::class . '"
(you need to lowercase the first letter from the class or you can use the class name itself), (*7)
You can combine validators simply via "|" ..., (*8)
e.g.: data-validator="notEmpty|maxLength(100)"
, (*9)
PS: you can add arguments comma separated or you can use serialize -> something like that -> in(' . serialize($selectableValues) . ')
, (*10)
If you want to use the HTML5 validation e.g. for min or max values, or for e.g. email then you can use "auto"., (*11)
e.g.: data-validator="auto"
, (*12)
By default we limit the submitted values to the values from the form e.g. for checkboxes, radios or select boxes. If you need to disable this,
you can use "non-strict". (not recommended), (*13)
e.g.: data-validator="non-strict"
, (*14)
By default we use the error messages from the validation exception class, but you can use your own error messages via:
"data-error-message--RULE_NAME_HERE" in the html., (*15)
e.g.: data-error-message--email="Email [%s] is not correct"
, (*16)
By default we don't add error messages into html output, but you can add the error messages with a css selector:, (*17)
e.g.: data-error-template-selector="span#email-error-message-template"
, (*18)
By default we also don't add error classes, but you can add a new error class via:, (*19)
e.g. data-error-class="error-foo-bar"
, (*20)
And if you need a more complex validation, then you can add simple-custom validations., (*21)
$formValidator->addCustomRule(
'foobar',
\Respect\Validation\Validator::allOf(
\Respect\Validation\Validator::intVal(),
\Respect\Validation\Validator::positive()
)
);
e.g.: data-validator="foobar"
, (*22)
And if you need really complex validation, then you can create your own classes., (*23)
<?php
namespace Respect\Validation\Rules;
class CustomRule extends AbstractRule
{
/**
* @param string $value
*
* @return bool
*/
public function validate($value)
{
return ($value === 'foobar');
}
}
<?php
namespace Respect\Validation\Exceptions;
class CustomRuleException extends ValidationException
{
public static $defaultTemplates = [
self::MODE_DEFAULT => [
self::STANDARD => 'Invalid input... \'foobar\' is only allowed here... ',
],
self::MODE_NEGATIVE => [
self::STANDARD => 'Invalid input... \'foobar\' is not allowed here... ',
],
];
}
$formValidator->addCustomRule('foobar', \Respect\Validation\Rules\CustomRule::class);
e.g.: data-validator="foobar"
, (*24)
Filter
You can also use some simple filters, that will be applied on the input-data., (*25)
- trim
- escape (htmlentities with ENT_QUOTES | ENT_HTML5)
- ... and all methods from here
e.g.: data-filter="strip_tags(<p>)"
, (*26)
PS: the first argument will be the submitted value from the user, (*27)
And also here you can combine some filters simply via "|" ..., (*28)
e.g.: data-filter="strip_tags|trim|escape"
, (*29)
... and you can also add custom filters by your own., (*30)
$formValidator->addCustomFilter(
'append_lall',
function ($input) {
return $input . 'lall';
}
);
e.g.: data-filter="append_lall"
, (*31)
Unit Test
1) Composer is a prerequisite for running the tests., (*32)
composer install voku/HtmlFormValidator
2) The tests can be executed by running this command from the root directory:, (*33)
./vendor/bin/phpunit
Support
For support and donations please visit Github | Issues | PayPal | Patreon., (*34)
For status updates and release announcements please visit Releases | Twitter | Patreon., (*35)
For professional support please contact me., (*36)
Thanks
- Thanks to GitHub (Microsoft) for hosting the code and a good infrastructure including Issues-Managment, etc.
- Thanks to IntelliJ as they make the best IDEs for PHP and they gave me an open source license for PhpStorm!
- Thanks to Travis CI for being the most awesome, easiest continous integration tool out there!
- Thanks to StyleCI for the simple but powerfull code style check.
- Thanks to PHPStan && Psalm for relly great Static analysis tools and for discover bugs in the code!