Cookbook - rlanvin/php-form GitHub Wiki

Recipes for different validation scenarii with the Form class.

A field is required depending on the value of another field

For example, the field "State" is required only if "Country" is "US".

$form = new Form\Validator([
	'country_code' => ['required', 'in' => $country_codes],
	'state' => ['required' => function($form) { return $form->country_code == 'US'; }]
]);

A field in a array of values

For example, the field "Groups" is a group of checkboxes, and multiple can be checked at one. An ID is POSTed for every checked group.

[
	'groups' => [1,2,5]
]

Method 1:

$valid_groups = range(1,10);
$form = new Form\Validator([
	'groups' => ['required', 'is_array', 'in' => $valid_groups]
]);

Method 2 (in this case "groups" will always be casted to an array):

$valid_groups = range(1,10);
$form = new Form\Validator([
	'groups' => ['required', 'is_array', 'each' => ['in' => $valid_groups]]
]);

Validating an assoc array

Let's assume you want to validate nested arrays, typically found in a API, like the following:

[
	'address' => [
		'street' => '',
		'postcode' => '',
		'city' => '',
		'country' => ''
	]
]

For that, you will simply need a sub-form.

$form = new Form\Validator([
	'address' => new Form\Validator([
		'street' => ['required', 'trim'],
		'postcode' => ['trim'],
		'city' => ['required', 'trim'],
		'country' => ['required', 'length' => [2,2]]
	])
]);

Validating an array of assoc arrays

This use case is probably more common in the context of an API rather that a POST from an HTML form, since you cannot post such a structure with an HTML form.

So let's assume you want to validate a list of items, each with an ID and a position. Both are required, the position must be a number and the ID must be in a list of valid IDs.

[
	'items' => [
		[
			'id' => 12,
			'position' => 1
		],
		[
			'id' => 21,
			'position' => 2
		]
	]
]
$valid_items = [
	1 => "Item 1",
	2 => "Item 2",
	...
];
$form = new Form\Validator([
	'items' => ['each' => new Form\Validator([
		'id' => ['required', 'in_keys' => $valid_items],
		'position' => ['required', 'integer']
	])]
]);