]> Dogcows Code - chaz/p5-CGI-Ex/blob - lib/CGI/Ex/Validate.pod
CGI::Ex 2.27
[chaz/p5-CGI-Ex] / lib / CGI / Ex / Validate.pod
1 =head1 NAME
2
3 CGI::Ex::Validate - The "Just Right" form validator with javascript in parallel
4
5 =head1 SYNOPSIS
6
7 use CGI::Ex::Validate;
8
9 # THE SHORT
10
11 my $errobj = CGI::Ex::Validate->new->validate($form, $val_hash);
12
13 # THE LONG
14
15 my $form = CGI->new;
16 # OR #
17 my $form = CGI::Ex->new; # OR CGI::Ex->get_form;
18 # OR #
19 my $form = {key1 => 'val1', key2 => 'val2'};
20
21
22 # simplest
23 my $val_hash = {
24 'group order' => [qw(username email email2)],
25 username => {
26 required => 1,
27 max_len => 30,
28 field => 'username',
29 # field is optional in this case - will use key name
30 },
31 email => {
32 required => 1,
33 max_len => 100,
34 type => 'email',
35 },
36 email2 => {
37 equals => 'email',
38 },
39 };
40
41 # ordered
42 my $val_hash = {
43 'group order' => [{
44 field => 'username', # field is not optional in this case
45 required => 1,
46 max_len => 30,
47 }, {
48 field => 'email',
49 required => 1,
50 max_len => 100,
51 }, {
52 field => 'email2',
53 equals => 'email',
54 }],
55 };
56
57
58 my $vob = CGI::Ex::Validate->new;
59 my $errobj = $vob->validate($form, $val_hash);
60 if ($errobj) {
61 # get errors back in any of several useful ways
62 my $error_heading = $errobj->as_string; # OR "$errobj";
63 my $error_list = $errobj->as_array; # ordered list of what when wrong
64 my $error_hash = $errobj->as_hash; # hash of arrayrefs of errors
65 } else {
66 # the form passed validation
67 }
68
69
70 my $js_uri_path = '/js/'; # static or dynamic URI path to find CGI/Ex/validate.js
71 my $form_name = "the_form"; # name of the form to attach javascript to
72
73 # generate javascript to validate an existing form
74 my $javascript = $vob->generate_js($val_hash, {
75 form_name => $form_name,
76 js_uri_path => $js_uri_path,
77 });
78
79 # OR let Validate create the form and javascript for you
80 my $form = $vob->generate_form($val_hash, {
81 form_name => $form_name, # will use a random name if not passed
82 js_uri_path => $js_uri_path,
83 });
84
85
86 =head1 DESCRIPTION
87
88 CGI::Ex::Validate is one of many validation modules. It aims to have
89 all of the basic data validation functions, avoid adding all of
90 the millions of possible types, while still giving the capability
91 for the developer to add their own types for the rare cases that
92 the basic ones don't suffice. Generally anything more than basic
93 validation probably needs programmatic or data based validation.
94
95 CGI::Ex::Validate also has full support for providing the same
96 validation in javascript. It provides methods for attaching the
97 javascript to existing forms. This ability is tightly integrated into
98 CGI::Ex::App, but it should be easy to add validation just about
99 anywhere using any type of controller.
100
101 As opposed to other kitchen sync validation modules, CGI::Ex::Validate
102 offers the simple types of validation, and makes it easy to add your
103 own custom types. Asside from custom and custom_js, all validation
104 markup is declarative.
105
106 =head1 METHODS
107
108 =over 4
109
110 =item C<new>
111
112 Used to instantiate the object. Arguments are either a hash, or hashref,
113 or nothing at all. Keys of the hash become the keys of the object.
114
115 =item C<get_validation>
116
117 Uses CGI::Ex::Conf::conf_read to read in the hash. conf_read will all passing
118 a filename or YAML string or a hashref.
119
120 =item C<get_validation_keys>
121
122 Takes the validation hashref returned from get_validation. Will return all
123 of the possible keys found in the validation hashref. This can be used to
124 check to see if extra items have been passed to validate. If a second
125 argument contains a form hash is passed, get_validation_keys will only
126 return the keys of groups that were validated.
127
128 my $key_hashref = $self->get_validation_keys($val_hash);
129
130 The keys of the hash are the names of the fields.
131
132 =item C<validate>
133
134 Arguments are a form hashref or cgi object, a validation hashref or
135 filename, and an optional what_was_validated arrayref (discussed
136 further later on). If a CGI object is passed, CGI::Ex::get_form will
137 be called on that object to turn it into a hashref. If a filename is
138 given for the validation, get_validation will be called on that
139 filename. If the what_was_validated_arrayref is passed - it will be
140 populated (pushed) with the field hashes that were actually validated
141 (anything that was skipped because of validate_if will not be in the
142 array).
143
144 If the form passes validation, validate will return undef. If it
145 fails validation, it will return a CGI::Ex::Validate::Error object.
146 If the 'raise_error' option has been set, validate will die with a
147 CGI::Ex::validate::Error object as the value.
148
149 my $err_obj = $self->validate($form, $val_hash);
150
151 # OR #
152
153 $self->{raise_error} = 1; # can also be listed in the val_hash
154 eval { $self->validate($form, $val_hash) };
155 if ($@) { my $err_obj = $@; }
156
157 =item C<generate_form>
158
159 Takes a validation hash, and additional arguments and generates an HTML form suitable
160 for inclusion in a web based application.
161
162 my $html = $self->generate_form($val_hash, {
163 form_name => 'my_form',
164 js_uri_path => '/cgi-bin/js', # will be used by generate_js
165 });
166
167 =item C<generate_js>
168
169 Works with CGI::Ex::JSONDump.
170
171 Takes a validation hash, a form name, and an optional javascript uri
172 path and returns Javascript that can be embedded on a page and will
173 perform identical validations as the server side. The form name must be
174 the name of the form that the validation will act upon - the name is
175 used to register an onsubmit function. The javascript uri path is
176 used to embed the locations of javascript source files included
177 with the CGI::Ex distribution.
178
179 The javascript uri path is highly dependent upon the server
180 configuration and therefore must be configured manually. It may be
181 passed to generate_js, or it may be specified in $JS_URI_PATH.
182 There is one file included with this module that is needed -
183 CGI/Ex/validate.js. When generating the js code, generate_js will
184 look in $JS_URI_PATH_VALIDATE. If this is not set,
185 generate_js will use "$JS_URI_PATH/CGI/Ex/validate.js".
186
187 my $js = $self->generate_js($val_hash, 'my_form', "/cgi-bin/js")
188 # OR
189 my $js = $self->generate_js($val_hash, {
190 form_name => 'my_form',
191 js_uri_path => '/cgi-bin/js',
192 });
193
194 # would generate something like the following...
195
196 <script src="/cgi-bin/js/CGI/Ex/validate.js"></script>
197 ... more js follows ...
198
199 $CGI::Ex::Validate::JS_URI_PATH = "/stock/js";
200 $self->generate_js($val_hash, 'my_form')
201
202 # would generate something like the following...
203
204 <script src="/stock/js/CGI/Ex/validate.js"></script>
205 ... more js follows ...
206
207 Referencing validate.js can be done in any of
208 several ways. It can be copied to or symlinked to a fixed location
209 in the server's html directory. It can also be printed out by a cgi.
210 The method C<-E<gt>print_js> has been provided in CGI::Ex for printing
211 js files found in the perl hierarchy. See L<CGI::Ex> for more details.
212 The $JS_URI_PATH of "/cgi-bin/js" could contain the following:
213
214 #!/usr/bin/perl -w
215
216 use strict;
217 use CGI::Ex;
218
219 # path_info should contain something like /CGI/Ex/validate.js
220 my $info = $ENV{PATH_INFO} || '';
221 die "Invalid path" if $info !~ m|^(/\w+)+.js$|;
222 $info =~ s|^/+||;
223
224 CGI::Ex->new->print_js($info);
225 exit;
226
227 The print_js method in CGI::Ex is designed to cache the javascript in
228 the browser.
229
230 =item C<-E<gt>cgix>
231
232 Returns a CGI::Ex object. Used internally if a CGI object is
233 passed to validate rather than a straight form hash.
234
235 =back
236
237 =head1 VALIDATION HASH
238
239 The validation hash may be passed as a hashref or as a filename, or as
240 a YAML document string. Experience has shown it to be better
241 programming to pass in a hashref. If the validation "hash" is a
242 filename or a YAML string, it will be translated into a hash using
243 CGI::Ex::Conf.
244
245 Keys matching the regex m/^group \s+ (\w+)$/x such as "group
246 onevent" are reserved and are counted as GROUP OPTIONS. Other keys
247 (if any, should be field names that need validation).
248
249 If the GROUP OPTION 'group validate_if' is set, the validation will
250 only be validated if the conditions of the validate_if are met. If
251 'group validate_if' is not specified, then the validation will
252 proceed. See the validate_if VALIDATION type for more information.
253
254 Each of the items listed in the validation will be validated. The
255 validation order is determined the following ways:
256
257 =over 4
258
259 =item Specify 'group order' arrayref with hashrefs.
260
261 # order will be (username, password, 'm/\w+_foo/', somethingelse)
262 {
263 'group title' => "User Information",
264 'group order' => [
265 {field => 'username', required => 1},
266 {field => 'password', required => 1},
267 {field => 'm/\w+_foo/', required => 1},
268 ],
269 somethingelse => {required => 1},
270 }
271
272 =item Specify 'group order' arrayref with field key names.
273
274 # order will be (username, password, 'm/\w+_foo/', somethingelse)
275 {
276 'group title' => "User Information",
277 'group order' => [qw(username password), 'm/\w+_foo/'],
278 username => {required => 1},
279 password => {required => 1},
280 'm/\w+_foo/' => {required => 1},
281 somethingelse => {required => 1},
282 }
283
284 =item Do nothing - use sorted order.
285
286 # order will be ('m/\w+_foo/', password, somethingelse, username)
287 {
288 'group title' => "User Information",
289 username => {required => 1},
290 password => {required => 1},
291 'm/\w+_foo/' => {required => 1},
292 somethingelse => {required => 1},
293 }
294
295 =back
296
297 Optionally the 'group order' may contain the word 'OR' as a special
298 keyword. If the item preceding 'OR' fails validation the item after
299 'OR' will be tested instead. If the item preceding 'OR' passes
300 validation the item after 'OR' will not be tested.
301
302 'group order' => [qw(zip OR postalcode state OR region)],
303
304 At this time, only "group onevent" submit works with this option.
305 Using OR is not needed if testing for one or more values -- instead you
306 should use min_in_set or max_in_set (OR is still useful for other cases).
307
308 'zip' => {
309 max_in_set: '1 of zip, postalcode',
310 },
311 'state' => {
312 max_in_set: '1 of state, region',
313 },
314
315 Each individual field validation hashref will operate on the field contained
316 in the 'field' key. This key may also be a regular expression in the
317 form of 'm/somepattern/'. If a regular expression is used, all keys
318 matching that pattern will be validated. If the field key is
319 not specified, the key from the top level hash will be used.
320
321 foobar => { # "foobar" is not used as key because field is specified
322 field => 'real_key_name',
323 required => 1,
324 },
325 real_key_name2 => {
326 required => 1,
327 },
328
329 Each of the individual field validation hashrefs should contain the
330 types listed in VALIDATION TYPES.
331
332 =head1 VALIDATION TYPES
333
334 This section lists the available validation types. Multiple instances
335 of the same type may be used for some validation types by adding a
336 number to the type (ie match, match2, match232). Multiple instances
337 are validated in sorted order. Types that allow multiple values are:
338 compare, custom, custom_js, equals, enum, match, required_if, sql,
339 type, validate_if, and replace (replace is a MODIFICATION TYPE).
340
341 =over 4
342
343 =item C<compare>
344
345 Allows for custom comparisons. Available types are
346 >, <, >=, <=, !=, ==, gt, lt, ge, le, ne, and eq. Comparisons
347 also work in the JS.
348
349 {
350 field => 'my_number',
351 match => 'm/^\d+$/',
352 compare1 => '> 100',
353 compare2 => '< 255',
354 compare3 => '!= 150',
355 }
356
357 =item C<custom>
358
359 Custom value - not available in JS. Allows for extra programming types.
360 May be either a boolean value predetermined before calling validate, or may be
361 a coderef that will be called during validation. If coderef is called, it will
362 be passed the field name, the form value for that name, and a reference to the
363 field validation hash. If the custom type returns false the element fails
364 validation and an error is added.
365
366 {
367 field => 'username',
368 custom => sub {
369 my ($key, $val, $type, $field_val_hash) = @_;
370 # do something here
371 return 0;
372 },
373 }
374
375 =item C<custom_js>
376
377 Custom value - only available in JS. Allows for extra programming types.
378 May be a javascript function (if fully declared in javascript), a string containing
379 a javascript function (that will be eval'ed into a real function),
380 a boolean value pre-determined before calling validate, or may be
381 section of javascript that will be eval'ed (the last value of
382 the eval'ed javascript will determine if validation passed). A false response indicates
383 the value did not pass validation. A true response indicates that it did. See
384 the samples/validate_js_0_tests.html page for a sample of usages.
385
386 {
387 field => 'date',
388 required => 1,
389 match => 'm|^\d\d\d\d/\d\d/\d\d$|',
390 match_error => 'Please enter date in YYYY/MM/DD format',
391 custom_js => "function (args) {
392 var t=new Date();
393 var y=t.getYear()+1900;
394 var m=t.getMonth() + 1;
395 var d=t.getDate();
396 if (m<10) m = '0'+m;
397 if (d<10) d = '0'+d;
398 (args.value > ''+y+'/'+m+'/'+d) ? 1 : 0;
399 }",
400 custom_js_error => 'The date was not greater than today.',
401 }
402
403 =item C<enum>
404
405 Allows for checking whether an item matches a set of options. In perl
406 the value may be passed as an arrayref. In the conf or in perl the
407 value may be passed of the options joined with ||.
408
409 {
410 field => 'password_type',
411 enum => 'plaintext||crypt||md5', # OR enum => [qw(plaintext crypt md5)],
412 }
413
414 =item C<equals>
415
416 Allows for comparison of two form elements. Can have an optional !.
417
418 {
419 field => 'password',
420 equals => 'password_verify',
421 },
422 {
423 field => 'domain1',
424 equals => '!domain2', # make sure the fields are not the same
425 }
426
427 =item C<had_error>
428
429 Typically used by a validate_if. Allows for checking if this item has had
430 an error.
431
432 {
433 field => 'alt_password',
434 validate_if => {field => 'password', had_error => 1},
435 }
436
437 This is basically the opposite of was_valid.
438
439 =item C<match>
440
441 Allows for regular expression comparison. Multiple matches may
442 be concatenated with ||. Available in JS.
443
444 {
445 field => 'my_ip',
446 match => 'm/^\d{1,3}(\.\d{1,3})3$/',
447 match_2 => '!/^0\./ || !/^192\./',
448 }
449
450 =item C<max_in_set> and C<min_in_set>
451
452 Somewhat like min_values and max_values except that you specify the
453 fields that participate in the count. Also - entries that are not
454 defined or do not have length are not counted. An optional "of" can
455 be placed after the number for human readability.
456
457 min_in_set => "2 of foo bar baz",
458 # two of the fields foo, bar or baz must be set
459 # same as
460 min_in_set => "2 foo bar baz",
461 # same as
462 min_in_set => "2 OF foo bar baz",
463
464 validate_if => {field => 'whatever', max_in_set => '0 of whatever'},
465 # only run validation if there were zero occurrences of whatever
466
467 =item C<max_len and min_len>
468
469 Allows for check on the length of fields
470
471 {
472 field => 'site',
473 min_len => 4,
474 max_len => 100,
475 }
476
477 =item C<max_values> and C<min_values>
478
479 Allows for specifying the maximum number of form elements passed.
480 max_values defaults to 1 (You must explicitly set it higher
481 to allow more than one item by any given name).
482
483 =item C<required>
484
485 Requires the form field to have some value. If the field is not present,
486 no other checks will be run.
487
488 =item C<required_if>
489
490 Requires the form field if the condition is satisfied. The conditions
491 available are the same as for validate_if. This is somewhat the same
492 as saying:
493
494 validate_if => 'some_condition',
495 required => 1
496
497 required_if => 'some_condition',
498
499 If a regex is used for the field name, the required_if
500 field will have any match patterns swapped in.
501
502 {
503 field => 'm/^(\w+)_pass/',
504 required_if => '$1_user',
505 }
506
507 This example would require the "foobar_pass" field to be set
508 if the "foobar_user" field was passed.
509
510 =item C<sql>
511
512 SQL query based - not available in JS. The database handle will be looked
513 for in the value $self->{dbhs}->{foo} if sql_db_type is set to 'foo',
514 otherwise it will default to $self->{dbh}. If $self->{dbhs}->{foo} or
515 $self->{dbh} is a coderef - they will be called and should return a dbh.
516
517 {
518 field => 'username',
519 sql => 'SELECT COUNT(*) FROM users WHERE username = ?',
520 sql_error_if => 1, # default is 1 - set to 0 to negate result
521 # sql_db_type => 'foo', # will look for a dbh under $self->{dbhs}->{foo}
522 }
523
524 =item C<type>
525
526 Allows for more strict type checking. Currently supported types
527 include CC (credit card), EMAIL, DOMAIN, IP, URL. Other types will be
528 added upon request provided we can add a perl and a javascript
529 version.
530
531 {
532 field => 'credit_card',
533 type => 'CC',
534 }
535
536 =item C<validate_if>
537
538 If validate_if is specified, the field will only be validated
539 if the conditions are met. Works in JS.
540
541 validate_if => {field => 'name', required => 1, max_len => 30}
542 # Will only validate if the field "name" is present and is less than 30 chars.
543
544 validate_if => 'name',
545 # SAME as
546 validate_if => {field => 'name', required => 1},
547
548 validate_if => '! name',
549 # SAME as
550 validate_if => {field => 'name', max_in_set => '0 of name'},
551
552 validate_if => 'name was_valid',
553 # SAME as
554 validate_if => {field => 'name', was_valid => 1},
555
556 validate_if => {field => 'country', compare => "eq US"},
557 # only if country's value is equal to US
558
559 validate_if => {field => 'country', compare => "ne US"},
560 # if country doesn't equal US
561
562 validate_if => {field => 'password', match => 'm/^md5\([a-z0-9]{20}\)$/'},
563 # if password looks like md5(12345678901234567890)
564
565 {
566 field => 'm/^(\w+)_pass/',
567 validate_if => '$1_user',
568 required => 1,
569 }
570 # will validate foo_pass only if foo_user was present.
571
572 The validate_if may also contain an arrayref of validation items. So that
573 multiple checks can be run. They will be run in order. validate_if will
574 return true only if all options returned true.
575
576 validate_if => ['email', 'phone', 'fax']
577
578 Optionally, if validate_if is an arrayref, it may contain the word
579 'OR' as a special keyword. If the item preceding 'OR' fails validation
580 the item after 'OR' will be tested instead. If the item preceding 'OR'
581 passes validation the item after 'OR' will not be tested.
582
583 validate_if => [qw(zip OR postalcode)],
584
585 =item C<was_valid>
586
587 Typically used by a validate_if. Allows for checking if this item has successfully
588 been validated.
589
590 {
591 field => 'password2',
592 validate_if => {field => 'password', was_valid => 1},
593 }
594
595 This is basically the opposite of had_error.
596
597 =back
598
599 =head1 SPECIAL VALIDATION TYPES
600
601 =over 4
602
603 =item C<field>
604
605 Specify which field to work on. Key may be a regex in the form
606 'm/\w+_user/'. This key is required in a hashref passed to 'group
607 order'. It can optionally be used with other types to specify a
608 different form element to operate on. On errors, if a non-default
609 error is found, $field will be swapped with the value found in field.
610
611 The field name may also be a regular expression in the
612 form of 'm/somepattern/'. If a regular expression is used, all keys
613 matching that pattern will be validated.
614
615 =item C<name>
616
617 Name to use for errors. If a name is not specified, default errors will use
618 "The field $field" as the name. If a non-default error is found, $name
619 will be swapped with this name.
620
621 =item C<delegate_error>
622
623 This option allows for any errors generated on a field to delegate to
624 a different field. If the field name was a regex, any patterns will
625 be swapped into the delegate_error value. This option is generally only
626 useful with the as_hash method of the error object (for inline errors).
627
628 {
629 field => 'zip',
630 match => 'm/^\d{5}/',
631 },
632 {
633 field => 'zip_plus4',
634 match => 'm/^\d{4}/',
635 delegate_error => 'zip',
636 },
637 {
638 field => 'm/^(id_[\d+])_user$/',
639 delegate_error => '$1',
640 },
641
642 =item C<exclude_js>
643
644 This allows the cgi to do checking while keeping the checks from
645 being run in JavaScript
646
647 {
648 field => 'cgi_var',
649 required => 1,
650 exclude_js => 1,
651 }
652
653 =item C<exclude_cgi>
654
655 This allows the js to do checking while keeping the checks from
656 being run in the cgi
657
658 {
659 field => 'js_var',
660 required => 1,
661 exclude_cgi => 1,
662 }
663
664 =item C<vif_disable>
665
666 Only functions in javascript. Will mark set the form element to
667 disabled if validate_if fails. It will mark it as enabled if
668 validate_if is successful. This item should normally only be used
669 when onevent includes "change" or "blur".
670
671 =back
672
673 =head1 MODIFYING VALIDATION TYPES
674
675 The following types will modify the form value before it is processed.
676 They work in both the perl and in javascript as well. The javascript
677 version changes the actual value in the form on appropriate form types.
678
679 =over 4
680
681 =item C<do_not_trim>
682
683 By default, validate will trim leading and trailing whitespace
684 from submitted values. Set do_not_trim to 1 to allow it to
685 not trim.
686
687 {field => 'foo', do_not_trim => 1}
688
689 =item C<trim_control_chars>
690
691 Off by default. If set to true, removes characters in the
692 \x00 to \x31 range (Tabs are translated to a single space).
693
694 {field => 'foo', trim_control_chars => 1}
695
696 =item C<replace>
697
698 Pass a swap pattern to change the actual value of the form.
699 Any perl regex can be passed but it is suggested that javascript
700 compatible regexes are used to make generate_js possible.
701
702 {field => 'foo', replace => 's/(\d{3})(\d{3})(\d{3})/($1) $2-$3/'}
703
704 =item C<default>
705
706 Set item to default value if there is no existing value (undefined
707 or zero length string).
708
709 {field => 'country', default => 'EN'}
710
711 =item C<to_upper_case> and C<to_lower_case>
712
713 Do what they say they do.
714
715 =item C<untaint>
716
717 Requires that the validated field has been also checked with
718 an enum, equals, match, compare, custom, or type check. If the
719 field has been checked and there are no errors - the field is "untainted."
720
721 This is for use in conjunction with perl's -T switch.
722
723 =item C<clear_on_error>
724
725 Clears the form field should a validation error occur. Only supported
726 on the Javascript side (no affect on the server side).
727
728 =back
729
730 =head1 ERROR OBJECT
731
732 Failed validation results in an error an error object created via the
733 new_error method. The default error class is CGI::Ex::Validate::Error.
734
735 The error object has several methods for determining what the errors were.
736
737 =over 4
738
739 =item C<as_array>
740
741 Returns an array or arrayref (depending on scalar context) of errors that
742 occurred in the order that they occurred. Individual groups may have a heading
743 and the entire validation will have a heading (the default heading can be changed
744 via the 'as_array_title' group option). Each error that occurred is a separate
745 item and are pre-pended with 'as_array_prefix' (which is a group option - default
746 is ' '). The as_array_ options may also be set via a hashref passed to as_array.
747 as_array_title defaults to 'Please correct the following items:'.
748
749 # if this returns the following
750 my $array = $err_obj->as_array;
751 # $array looks like
752 # ['Please correct the following items:', ' error1', ' error2']
753
754 # then this would return the following
755 my $array = $err_obj->as_array({
756 as_array_prefix => ' - ',
757 as_array_title => 'Something went wrong:',
758 });
759 # $array looks like
760 # ['Something went wrong:', ' - error1', ' - error2']
761
762 =item C<as_string>
763
764 Returns values of as_array joined with a newline. This method is used as
765 the stringification for the error object. Values of as_array are joined with
766 'as_string_join' which defaults to "\n". If 'as_string_header' is set, it will
767 be pre-pended onto the error string. If 'as_string_footer' is set, it will be
768 appended onto the error string.
769
770 # if this returns the following
771 my $string = $err_obj->as_string;
772 # $string looks like
773 # "Please correct the following items:\n error1\n error2"
774
775 # then this would return the following
776 my $string = $err_obj->as_string({
777 as_array_prefix => ' - ',
778 as_array_title => 'Something went wrong:',
779 as_string_join => '<br />',
780 as_string_header => '<span class="error">',
781 as_string_footer => '</span>',
782 });
783 # $string looks like
784 # '<span class="error">Something went wrong:<br /> - error1<br /> - error2</span>'
785
786 =item C<as_hash>
787
788 Returns a hash or hashref (depending on scalar context) of errors that
789 occurred. Each key is the field name of the form that failed
790 validation with 'as_hash_suffix' added on as a suffix. as_hash_suffix
791 is available as a group option and may also be passed in via a
792 hashref as the only argument to as_hash. The default value is
793 '_error'. The values of the hash are arrayrefs of errors that
794 occurred to that form element.
795
796 By default as_hash will return the values of the hash as arrayrefs (a
797 list of the errors that occurred to that key). It is possible to also
798 return the values as strings. Three options are available for
799 formatting: 'as_hash_header' which will be pre-pended onto the error
800 string, 'as_hash_footer' which will be appended, and 'as_hash_join'
801 which will be used to join the arrayref. The only argument required
802 to force the stringification is 'as_hash_join'.
803
804 # if this returns the following
805 my $hash = $err_obj->as_hash;
806 # $hash looks like
807 # {key1_error => ['error1', 'error2']}
808
809 # then this would return the following
810 my $hash = $err_obj->as_hash({
811 as_hash_suffix => '_foo',
812 as_hash_join => '<br />',
813 as_hash_header => '<span class="error">'
814 as_hash_footer => '</span>'
815 });
816 # $hash looks like
817 # {key1_foo => '<span class="error">error1<br />error2</span>'}
818
819 =back
820
821 =head1 GROUP OPTIONS
822
823 Any key in a validation hash matching the pattern
824 m/^group \s+ (\w+)$/x is considered a group option (the reason
825 that either group or general may be used is that CGI::Ex::Validate
826 used to have the concept of validation groups - these were not
827 commonly used so support has been removed as of the 2.10 release).
828 (the old name of 'general' vs 'group' is still supported but deprecated)
829
830 =over 4
831
832 =item C<title>
833
834 Used as a group section heading when as_array or as_string is called
835 by the error object.
836
837 'group title' => 'Title of errors',
838
839 =item C<order>
840
841 Order in which to validate key/value pairs of group.
842
843 'group order' => [qw(user pass email OR phone)],
844
845 # OR
846
847 'group order' => [{
848 field => 'field1',
849 required => 1,
850 }, {
851 field => 'field2',
852 required => 1,
853 }],
854
855 =item C<fields>
856
857 Alias for 'group order'.
858
859 =item C<validate_if>
860
861 If specified - the entire hashref will only be validated if
862 the "if" conditions are met.
863
864 'group validate_if => {field => 'email', required => 1},
865
866 This group would only validate all fields if the email field
867 was present.
868
869 =item C<raise_error>
870
871 If raise_error is true, any call to validate that fails validation
872 will die with an error object as the value.
873
874 =item C<no_extra_fields>
875
876 If no_extra_fields is true, validate will add errors for any field found
877 in form that does not have a field_val hashref in the validation hash.
878 Default is false. If no_extra_fields is set to 'used', it will check for
879 any keys that were not in a group that was validated.
880
881 An important exception to this is that field_val hashrefs or field names listed
882 in a validate_if or required_if statement will not be included. You must
883 have an explicit entry for each key.
884
885 =item C<\w+_error>
886
887 These items allow for an override of the default errors.
888
889 'group required_error' => '$name is really required',
890 'group max_len_error' => '$name must be shorter than $value characters',
891 # OR #
892 my $self = CGI::Ex::Validate->new({
893 max_len_error => '$name must be shorter than $value characters',
894 });
895
896 =item C<as_array_title>
897
898 Used as the section title for all errors that occur, when as_array
899 or as_string is called by the error object.
900
901 =item C<as_array_prefix>
902
903 Used as prefix to individual errors that occur, when as_array
904 or as_string is called by the error object. Each individual error
905 will be prefixed with this string. Headings will not be prefixed.
906 Default is ' '.
907
908 =item C<as_string_join>
909
910 When as_string is called, the values from as_array will be joined with
911 as_string_join. Default value is "\n".
912
913 =item C<as_string_header>
914
915 If set, will be pre-pended onto the string when as_string is called.
916
917 =item C<as_string_footer>
918
919 If set, will be pre-pended onto the string when as_string is called.
920
921 =item C<as_hash_suffix>
922
923 Added on to key names during the call to as_hash. Default is '_error'.
924
925 =item C<as_hash_join>
926
927 By default, as_hash will return hashref values that are errors joined with
928 the default as_hash_join value of <br />. It can also return values that are
929 arrayrefs of the errors. This can be done by setting as_hash_join to a non-true value
930 (for example '')
931
932 =item C<as_hash_header>
933
934 If as_hash_join has been set to a true value, as_hash_header may be set to
935 a string that will be pre-pended on to the error string.
936
937 =item C<as_hash_footer>
938
939 If as_hash_join has been set to a true value, as_hash_footer may be set to
940 a string that will be postpended on to the error string.
941
942 =item C<onevent>
943
944 Defaults to {submit => 1}. This controls when the javascript validation
945 will take place. May be passed any or all or load, submit, change, or blur.
946 Multiple events may be passed in the hash.
947
948 'group onevent' => {submit => 1, change => 1}',
949
950 A comma separated string of types may also be passed:
951
952 'group onevent' => 'submit,change,blur,load',
953
954 Currently, change and blur will not work for dynamically matched
955 field names such as 'm/\w+/'. Support will be added.
956
957 =item C<set_hook>
958
959 Defaults document.validate_set_hook which defaults to nothing. If
960 "group set_hook" or document.validate_set_hook are set to a function,
961 they will be passed the key name of a form element that had a
962 validation error and the error that will be set. If a true value is
963 returned, then validate will not also the inline error. If no value
964 or false is returned (default) the validate will continue setting the
965 inline error. This gives full control over setting inline
966 errors. samples/validate_js_2_onchange.html has a good example of
967 using these hooks.
968
969 'group set_hook' => "function (args) {
970 alert("Setting error to field "+args.key);
971 }",
972
973 The args parameter includes key, value, val_hash, and form.
974
975 The document.validate_set_hook option is probably the better option to use,
976 as it helps to separate display functionality out into your html templates
977 rather than storing too much html logic in your CGI.
978
979 =item C<clear_hook>
980
981 Similar to set_hook, but called when inline error is cleared. Its
982 corresponding default is document.validate_clear_hook. The clear hook
983 is also sampled in samples/validate_js_2_onchange.html
984
985 'group clear_hook' => "function (args) {
986 alert("Clear error on field "+args.key);
987 }",
988
989 The args parameter includes key, val_hash, form, and was_valid.
990
991 =item C<no_inline>
992
993 If set to true, the javascript validation will not attempt to generate
994 inline errors when the only "group onevent" type is "submit". Default
995 is true. Inline errors are independent of confirm and alert errors.
996
997 'group no_inline' => 1,
998
999 =item C<no_confirm>
1000
1001 If set to true, the javascript validation will try to use an alert
1002 instead of a confirm to inform the user of errors when one of the
1003 "group onevent" types is "submit". Alert and confirm are independent
1004 or inline errors. Default is false.
1005
1006 'group no_confirm' => 1,
1007
1008 =item C<no_alert>
1009
1010 If set to true, the javascript validation will not show an alert box
1011 when errors occur. Default is false. This option only comes into
1012 play if no_confirm is also set. This option is only in effect if
1013 "group onevent" includes "submit". This option is independent of
1014 inline errors. Although it is possible to turn off all errors by
1015 setting no_inline, no_confirm, and no_alert all to 1, it is suggested
1016 that at least one of the error reporting facilities is left on.
1017
1018 'group no_alert' => 1,
1019
1020 =back
1021
1022 =head1 JAVASCRIPT
1023
1024 CGI::Ex::Validate provides for having duplicate validation on the
1025 client side as on the server side. Errors can be shown in any
1026 combination of inline and confirm, inline and alert, inline only,
1027 confirm only, alert only, and none. These combinations are controlled
1028 by the group options no_inline, no_confirm, and no_alert.
1029 Javascript validation can be generated for a page using the
1030 C<-E<gt>generate_js> method of CGI::Ex::Validate.
1031
1032 (Note: It is also possible to store the validation inline with the
1033 html as YAML and have it read in using the HTML conf handler - but
1034 this feature has been deprecated - see the included html samples for
1035 how to do this).
1036
1037 Generate JS will create something similar to the following (based on your validation):
1038
1039 <script src="/cgi-bin/js/CGI/Ex/validate.js"></script>
1040 <script>
1041 document.validation = {
1042 'group no_confirm': 1,
1043 'group no_alert': 1,
1044 'group onevent': 'change,blur,submit',
1045 'group order': ['username', 'password'],
1046 username: {
1047 required: 1,
1048 max_len: 20
1049 },
1050 password: {
1051 required: 1,
1052 max_len: 30
1053 }
1054 };
1055 if (document.check_form) document.check_form('my_form_name');
1056 </script>
1057
1058 If inline errors are enabled (default), each error that occurs will attempt
1059 to find an html element with its name as the id. For example, if
1060 the field "username" failed validation and created a "username_error",
1061 the javascript would set the html of <span id="username_error"></span>
1062 to the error message.
1063
1064 It is suggested to use something like the following so that you can
1065 have inline javascript validation as well as report validation errors
1066 from the server side as well.
1067
1068 <span class=error id=password_error>[% password_error %]</span><br>
1069
1070 If the javascript fails for some reason, the form should still be able
1071 to submit as normal (fail gracefully).
1072
1073 Additionally, there are two hooks that are called when ever an inline
1074 error is set or cleared. The following hooks are used in
1075 samples/validate_js_2_onchange.html to highlight the row and set an icon.
1076
1077 document.validate_set_hook = function (args) {
1078 document.getElementById(args.key+'_img').innerHTML
1079 = '<span style="font-weight:bold;color:red">!</span>';
1080 document.getElementById(args.key+'_row').style.background
1081 = '#ffdddd';
1082 };
1083
1084 document.validate_clear_hook = function (args) {
1085 if (args.was_valid) {
1086 document.getElementById(args.key+'_img').innerHTML
1087 = '<span style="font-weight:bold;color:green">+</span>';
1088 document.getElementById(args.key+'_row').style.background
1089 = '#ddffdd';
1090 } else {
1091 document.getElementById(args.key+'_img').innerHTML = '';
1092 document.getElementById(args.key+'_row').style.background = '#fff';
1093 }
1094 };
1095
1096 These hooks can also be set as "group clear_hook" and "group set_hook"
1097 which are defined further above.
1098
1099 If the confirm option is used ("group onevent" includes submit and
1100 "group no_confirm" is false), the errors will be displayed to the
1101 user. If they choose OK they will be able to try and fix the errors.
1102 If they choose cancel, the form will submit anyway and will rely on
1103 the server to do the validation. This is for fail safety to make sure
1104 that if the javascript didn't validate correctly, the user can still
1105 submit the data.
1106
1107 =head1 THANKS
1108
1109 Thanks to Eamon Daly for providing bug fixes for bugs in validate.js
1110 caused by HTML::Prototype.
1111
1112 =head1 LICENSE
1113
1114 This module may be distributed under the same terms as Perl itself.
1115
1116 =head1 AUTHOR
1117
1118 Paul Seamons <paul at seamons dot com>
1119
1120 =cut
This page took 0.07688 seconds and 4 git commands to generate.