File: custom-validator.php

package info (click to toggle)
php-nette 2.4-20160731-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 3,208 kB
  • ctags: 7,552
  • sloc: php: 31,410; makefile: 6
file content (66 lines) | stat: -rw-r--r-- 1,417 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php

/**
 * Nette Forms custom validator example.
 */


if (@!include 'Nette/loader.php') {
	die('Install packages using `composer install`');
}

use Nette\Forms\Form;
use Tracy\Debugger;
use Tracy\Dumper;

Debugger::enable();


// Define custom validator
class MyValidators
{
	static function divisibilityValidator($item, $arg)
	{
		return $item->value % $arg === 0;
	}
}


$form = new Form;

$form->addText('num1', 'Multiple of 8:')
	->setDefaultValue(5)
	->addRule('MyValidators::divisibilityValidator', 'First number must be %d multiple', 8);

$form->addText('num2', 'Not multiple of 5:')
	->setDefaultValue(5)
	->addRule(~'MyValidators::divisibilityValidator', 'Second number must not be %d multiple', 5); // negative

$form->addSubmit('submit', 'Send');


if ($form->isSuccess()) {
	echo '<h2>Form was submitted and successfully validated</h2>';
	Dumper::dump($form->getValues());
	exit;
}


?>
<!DOCTYPE html>
<meta charset="utf-8">
<title>Nette Forms custom validator example</title>
<link rel="stylesheet" media="screen" href="assets/style.css" />
<script src="https://nette.github.io/resources/js/netteForms.js"></script>

<script>
	Nette.validators.MyValidators_divisibilityValidator = function(elem, args, val) {
		return val % args === 0;
	};
</script>

<h1>Nette Forms custom validator example</h1>

<?php echo $form ?>

<footer><a href="https://doc.nette.org/en/forms">see documentation</a></footer>