|
| 1 | +# Optional Input Filters |
| 2 | + |
| 3 | +- Since 2.8.0 |
| 4 | + |
| 5 | +Normally, input filters are _required_, which means that if you compose them as |
| 6 | +a subset of another input filter (e.g., to validate a subset of a larger set of |
| 7 | +data), and no data is provided for that item, or an empty set of data is |
| 8 | +provided, then the input filter will consider the data invalid. |
| 9 | + |
| 10 | +If you want to allow a set of data to be empty, you can use |
| 11 | +`Zend\InputFilter\OptionalInputFilter`. |
| 12 | + |
| 13 | +To illustrate this, let's consider a form where a user provides profile |
| 14 | +information. The user can provide an optional "title" and a required "email", |
| 15 | +and _optionally_ details about a project they lead, which will include the |
| 16 | +project title and a URL, both of which are required if present. |
| 17 | + |
| 18 | +First, let's create an `OptionalInputFilter` instance for the project data: |
| 19 | + |
| 20 | +```php |
| 21 | +$projectFilter = new OptionalInputFilter(); |
| 22 | +$projectFilter->add([ |
| 23 | + 'name' => 'project_name', |
| 24 | + 'required' => true, |
| 25 | +]); |
| 26 | +$projectFilter->add([ |
| 27 | + 'name' => 'url', |
| 28 | + 'required' => true, |
| 29 | + 'validators' => [ |
| 30 | + ['type' => 'uri'], |
| 31 | + ], |
| 32 | +]); |
| 33 | +``` |
| 34 | + |
| 35 | +Now, we'll create our primary input filter: |
| 36 | + |
| 37 | +```php |
| 38 | +$profileFilter = new InputFilter(); |
| 39 | +$profileFilter->add([ |
| 40 | + 'name' => 'title', |
| 41 | + 'required' => false, |
| 42 | +]); |
| 43 | +$profileFilter->add([ |
| 44 | + 'name' => 'email', |
| 45 | + 'required' => true, |
| 46 | + 'validators' => [ |
| 47 | + ['type' => 'EmailAddress'], |
| 48 | + ], |
| 49 | +]); |
| 50 | + |
| 51 | +// And, finally, compose our project sub-filter: |
| 52 | +$profileFilter->add($projectFilter, 'project'); |
| 53 | +``` |
| 54 | + |
| 55 | +With this defined, we can now validate the following sets of data, presented in |
| 56 | +JSON for readability: |
| 57 | + |
| 58 | +- Just profile information: |
| 59 | + |
| 60 | + ```json |
| 61 | + { |
| 62 | + |
| 63 | + "title": "Software Developer" |
| 64 | + } |
| 65 | + ``` |
| 66 | + |
| 67 | +- `null` project provided: |
| 68 | + |
| 69 | + ```json |
| 70 | + { |
| 71 | + |
| 72 | + "title": "Software Developer", |
| 73 | + "project": null |
| 74 | + } |
| 75 | + ``` |
| 76 | + |
| 77 | +- Empty project provided: |
| 78 | + |
| 79 | + ```json |
| 80 | + { |
| 81 | + |
| 82 | + "title": "Software Developer", |
| 83 | + "project": {} |
| 84 | + } |
| 85 | + ``` |
| 86 | + |
| 87 | +- Valid project provided: |
| 88 | + |
| 89 | + ```json |
| 90 | + { |
| 91 | + |
| 92 | + "title": "Software Developer", |
| 93 | + "project": { |
| 94 | + "project_name": "zend-inputfilter", |
| 95 | + "url": "https://github.com/zend-inputfilter", |
| 96 | + } |
| 97 | + } |
| 98 | + ``` |
0 commit comments