1HTML::FormHandler::ManuUasle:r:VCaolnitdraitbiuotne(d3H)PTeMrLl::DFoocrummHeanntdalteiro:n:Manual::Validation(3)
2
3
4
6 HTML::FormHandler::Manual::Validation - validating fields
7
9 version 0.40068
10
12 Manual Index
13
14 There are many options for validating fields in FormHandler. Some
15 validation is from field attributes, some from form or field methods,
16 some from 'apply' actions on the fields.
17
19 Each individual field may have additional attributes that relate to
20 validation, which are not documented here. See the individual field
21 documentation, linked from HTML::FormHandler::Manual::Fields.
22
23 required, required_when
24 Setting the 'required' flag on a field initiates a check for the
25 existence of some value. If the field does not have a value, the
26 'required' error message is issued.
27
28 has_field 'section' => ( required => 1,
29 messages => { required => 'Please provide a section' } );
30
31 Note that a required flag on a subfield -- a field inside a compound
32 field or repeatable field -- does not cause the containing field to be
33 required. You need to set 'required' all the way up, if that's the
34 behavior that you want.
35
36 If a field is empty and *not* required, no other field validation will
37 be performed unless the 'validate_when_empty' flag (see below) is set.
38 The form's 'validate' method, however, will always be called.
39
40 There is also the 'required_when' attribute, which works the same way
41 as the 'when' key on the apply actions.
42
43 has_field 'fee' => ( required_when => { 'fie' => 2 } );
44
45 When a 'required' or 'required_when' check fails, a 'missing' flag is
46 set in the result:
47
48 if ( $field->missing ) { ... }
49
50 range_start, range_end
51 Starting and ending range for number fields.
52
53 unique
54 Attribute used by the DBIC model to check for uniqueness.
55
56 validate_when_empty
57 If its 'validate_when_empty' flag is set to a true value, then a field
58 will always undergo validation when its form is processed, even when
59 that field is empty.
60
62 validate_method
63 You can provide a validation method for a field by setting a coderef
64 with 'validate_method'.
65
66 has_field 'fox' => ( validate_method => \&check_fox );
67 sub check_fox {
68 my $self = shift; # self is the fox field
69 unless( $self->value eq .... ) {
70 $self->add_error('....');
71 }
72 }
73
74 validate_<field_name>
75 If you provide a 'validate_<field_name>' method it will be
76 automatically used.
77
78 has_field 'cat';
79 sub validate_cat {
80 my ( $self, $field ) = @_; # self is the form
81 unless ( $field->value eq ... ) {
82 $field->add_error( '...' );
83 }
84 }
85
86 If the field name has periods in it, they should be replaced with
87 underscores.
88
89 form validate method
90 A form validation method can be used to do cross-validation or
91 validation checks that need information from more than one field.
92
93 sub validate {
94 my $self = shift;
95 $self->field('foo')->add_error('....')
96 if( $self->field('foo')->value eq '..' &&
97 $self->field('bar')->value eq '..' );
98 }
99
100 field validate method
101 You can create a custom field to contain a commonly used validation.
102 The validation in a custom field can be done with 'apply' or by using a
103 'validate' method.
104
105 package MyApp::Form::Field::Custom;
106 use HTML::FormHandler::Moose;
107 extends 'HTML::FormHandler::Field'; # or a subclass of Field
108
109 sub validate {
110 ....
111 }
112
114 The actions in the 'apply' array (stored in the 'actions' attribute)
115 will be performed in the order they are specified, allowing fine-
116 grained control over inflation and validation. You can check
117 constraints after transformations and vice versa. You can weave all
118 three types of actions in any order you need.
119
120 The two valid 'apply' array elements are 1) Moose types and 2) hashrefs
121 with one of three keys: 'check', 'transform', and 'type'. The hashrefs
122 will usually also have an additional key, 'message', with a string,
123 array or coderef providing an error message, which is localized.
124
125 The 'check' key can point to a regex, arrayref of strings, or coderef.
126 The value of the 'transform' key should be a coderef. The value of the
127 'type' key is a Moose type.
128
129 In addition to the check and type keys, you can provide a 'when' key to
130 only perform this validation when a particular field is a particular
131 value:
132
133 has_field 'fee';
134 has_field 'fie' => ( apply => [
135 { when => { fee => 1 }, check => qr/when/, message => 'Wrong fie' },
136 ]);
137 has_field 'fo';
138 has_field 'fum_comp' => ( type => 'Compound' );
139 has_field 'fum_comp.one';
140 has_field 'fum_comp.two' => ( apply => [
141 { when => { '+fee' => [1,2,3] }, check => qr/when/, message => 'Wrong two' },
142 ]);
143
144 The field name key in the 'when' hashref is assumed to be a field at
145 the same "level" as this field (i.e. a sibling field in a compound). If
146 you want to specify a field name from the form, prepend the name with a
147 '+'.
148
149 The 'when' hashref can contain multiple key/value pairs. This simply
150 extends its test across multiple fields; all fields named in the
151 hashref's keys must match their respective values in order for the
152 overall 'when' test to pass.
153
154 when => { foo => 3 } # when the foo field value is 3
155 when => { foo => [1,2,3]} # when foo is 1, 2, or 3
156 when => { foo => sub { $_[0] > 0 }} # when foo is greater than 0
157 when => { foo => sub { $_[0] ne ''}} # when foo is the empty string
158
159 Transformations and coercions are called in an eval to catch the
160 errors. Warnings are trapped in a sigwarn handler.
161
162 If the conditions get too complicated to easily fit into a when
163 condition, you can always create a validation method instead.
164
165 See also HTML::FormHandler::Field and HTML::FormHandler::Validate. See
166 HTML::FormHandler::Manual::InflationDeflation for information on
167 inflation and deflation.
168
169 Moose types
170 Moose types can be used to do both constraints and transformations. If
171 a coercion exists it will be applied, resulting in a transformation.
172 After coercing, the result is checked. You can use type constraints
173 from MooseX::Types libraries or defined using
174 Moose::Util::TypeConstraints.
175
176 FormHandler supplies a library of Moose types in
177 HTML::FormHandler::Types.
178
179 use HTML::FormHandler::Types ('NotAllDigits');
180 has_field 'foo' => ( apply => [ NotAllDigits ] );
181
182 You can create your own library of types, too. Or you can create a type
183 constraint in the form:
184
185 use Moose::Util::TypeConstraints;
186 subtype 'GreaterThan10'
187 => as 'Int'
188 => where { $_ > 10 }
189 => message { "This number ($_) is not greater than 10" };
190
191 has_field 'text_gt' => ( apply=> [ 'GreaterThan10' ] );
192
193 Moose types can also be used for their coercions to do transformations.
194
195 subtype 'MyInt'
196 => as 'Int';
197 coerce 'MyInt'
198 => from 'MyStr'
199 => via { return $1 if /(\d+)/ };
200
201 You can also use the 'type' keyword with a Moose type if you want to
202 change the message:
203
204 has_field 'text_gt' => ( apply => [
205 { type => 'GreaterThan10',
206 message => 'Number is too small' } ] );
207
208 transform
209 A 'transform' changes the format of a field's value, and does not need
210 a message. It takes a coderef.
211
212 has_field 'another_field' => (
213 apply => [ { transform => sub{ sprintf '<%.1g>', $_[0] } } ]
214 );
215
216 Note that transformed values are not displayed in the HTML form unless
217 the 'fif_from_value' flag is set. The transformed values are saved to
218 the database or returned in "$form->value".
219
220 'check' regex
221 Checks that field value matches the regex.
222
223 has_field 'some_field' => (
224 apply => [ { check => qr/aaa/, message => 'Must contain aaa' } ],
225 );
226
227 You can use regex libraries like Regexp::Common too:
228
229 use Regexp::Common ('URI');
230 ...
231 has_field 'my_url' => ( apply => [
232 { check => qr/$RE{URI}{HTTP}/,
233 message => 'Invalid URL' } ] );
234
235 'check' arrayref (matches)
236 Provide an arrayref of strings to match against.
237
238 has_field 'set_error' => (
239 apply => [
240 { check => [ 'abc', 'bbb' ],
241 message => 'Must be "aaa" or "bbb"' }
242 ]
243 );
244
245 'check' coderef
246 Provide a validation function to check. A 'check' coderef will be
247 passed the current value of the field and should return true or false.
248 Note that the field is passed in as the second argument, to allow
249 simple functions to work properly.
250
251 has_field 'callback_pass' => (
252 apply => [
253 { check => \&check_callback_pass,
254 message => 'Must contain number greater than 10', }
255 ]
256 );
257 sub check_callback_pass {
258 my ( $value, $field ) = @_;
259 if( $value =~ /(\d+)/ ) {
260 return $1 > 10;
261 }
262 }
263
264 message
265 The message for the above checks can also be an arrayref or coderef.
266 The arrayref is useful for localized messages. You can also provide
267 error messages for Moose types.
268
269 has_field 'message_sub' => (
270 apply => [
271 { check => [ 'abc' ],
272 message => \&err_message }
273 ]
274 );
275 sub err_message {
276 my ($value, $field ) = @_;
277 return $field->name . ': Must be "abc"';
278 }
279 has_field 'message_arrayref' => (
280 apply => [ { check => qr/aaa/,
281 message => ['Must contain [_1]', 'aaa'] } ],
282 );
283 has_field 'my_moose_type_field' => (
284 apply => [ { type => SomeType,
285 message => 'Invalid ...' } ] );
286
287 actions in a field class
288 To declare actions inside a field class use HTML::FormHandler::Moose
289 and 'apply' sugar:
290
291 package MyApp::Field::Test;
292 use HTML::FormHandler::Moose;
293 extends 'HTML::FormHandler::Field;
294
295 apply [ 'SomeConstraint', { check => ..., message => .... } ];
296
297 1;
298
299 Actions specified with apply are cumulative. Actions may be specified
300 in field classes and additional actions added in the 'has_field'
301 declaration.
302
303 You can see examples of field classes with 'apply' actions in the
304 source for HTML::FormHandler::Field::Money and
305 HTML::FormHandler::Field::Email, and in t/constraints.t.
306
308 The 'dependency' attribute is an array of arrays of field names.
309 During validation, if any field in a given group has a value that
310 matches the pattern /\S/ (non-blank), the 'required' flag is set for
311 all of the fields in the group.
312
313 has '+dependency' => ( default => sub {
314 [
315 ['address', 'city', 'state', 'zip'],
316 ['cc_no', 'cc_expires'],
317 ],
318 },
319 );
320
321 You can also use the 'required_when' flag to do something similar.
322
324 FormHandler Contributors - see HTML::FormHandler
325
327 This software is copyright (c) 2017 by Gerda Shank.
328
329 This is free software; you can redistribute it and/or modify it under
330 the same terms as the Perl 5 programming language system itself.
331
332
333
334perl v5.30.1 2020-H0T1M-L3:0:FormHandler::Manual::Validation(3)