| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Nette Forms custom validator example. |
| 5 |
*/ |
| 6 |
declare (strict_types=1); |
| 7 |
namespace Packetery; |
| 8 |
|
| 9 |
if (@(!(include __DIR__ . '/../vendor/autoload.php'))) { |
| 10 |
die('Install packages using `composer install`'); |
| 11 |
} |
| 12 |
use Packetery\Nette\Forms\Form; |
| 13 |
use Packetery\Tracy\Debugger; |
| 14 |
use Packetery\Tracy\Dumper; |
| 15 |
Debugger::enable(); |
| 16 |
// Define custom validator |
| 17 |
class MyValidators |
| 18 |
{ |
| 19 |
public static function divisibilityValidator($item, $arg) : bool |
| 20 |
{ |
| 21 |
return $item->value % $arg === 0; |
| 22 |
} |
| 23 |
} |
| 24 |
$form = new Form(); |
| 25 |
$form->addText('num1', 'Multiple of 8:')->setDefaultValue(5)->addRule('MyValidators::divisibilityValidator', 'First number must be %d multiple', 8); |
| 26 |
$form->addSubmit('submit', 'Send'); |
| 27 |
if ($form->isSuccess()) { |
| 28 |
echo '<h2>Form was submitted and successfully validated</h2>'; |
| 29 |
Dumper::dump($form->getValues()); |
| 30 |
exit; |
| 31 |
} |
| 32 |
?> |
| 33 |
<!DOCTYPE html> |
| 34 |
<meta charset="utf-8"> |
| 35 |
<title>Nette Forms custom validator example</title> |
| 36 |
<link rel="stylesheet" media="screen" href="assets/style.css" /> |
| 37 |
<script src="https://nette.github.io/resources/js/3/netteForms.js"></script> |
| 38 |
|
| 39 |
<script> |
| 40 |
Nette.validators.MyValidators_divisibilityValidator = function(elem, args, val) { |
| 41 |
return val % args === 0; |
| 42 |
}; |
| 43 |
</script> |
| 44 |
|
| 45 |
<h1>Nette Forms custom validator example</h1> |
| 46 |
|
| 47 |
<?php |
| 48 |
$form->render(); |
| 49 |
?> |
| 50 |
|
| 51 |
<footer><a href="https://doc.nette.org/en/forms">see documentation</a></footer> |
| 52 |
<?php |
| 53 |
|