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