1CGI::Ex::Validate(3)  User Contributed Perl Documentation CGI::Ex::Validate(3)
2
3
4

NAME

6       CGI::Ex::Validate - another form validator - but it does javascript in
7       parallel
8

SYNOPSIS

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           ### simplest
25           my $val_hash = {
26               username => {
27                   required => 1,
28                   max_len  => 30,
29                   field    => 'username',
30                   # field is optional in this case - will use key name
31               },
32               email    => {
33                   required => 1,
34                   max_len  => 100,
35               },
36               email2   => {
37                   validate_if => 'email',
38                   equals      => 'email',
39               },
40           };
41
42           ### ordered
43           my $val_hash = {
44               'group order' => [qw(username email email2)],
45               username => {required => 1, max_len => 30},
46               email    => ...,
47               email2   => ...,
48           };
49
50           ### ordered again
51           my $val_hash = {
52               'group fields' => [{
53                   field    => 'username', # field is not optional in this case
54                   required => 1,
55                   max_len  => 30,
56               }, {
57                   field    => 'email',
58                   required => 1,
59                   max_len  => 100,
60               }, {
61                   field       => 'email2',
62                   validate_if => 'email',
63                   equals      => 'email',
64               }],
65           };
66
67           my $vob    = CGI::Ex::Validate->new;
68           my $errobj = $vob->validate($form, $val_hash);
69           # OR #
70           my $errobj = $vob->validate($form, "/somefile/somewhere.val"); # import config using yaml file
71           # OR #
72           my $errobj = $vob->validate($form, "/somefile/somewhere.pl");  # import config using perl file
73           # OR #
74           my $errobj = $vob->validate($form, "--- # a yaml document\n"); # import config using yaml str
75
76           if ($errobj) {
77               my $error_heading = $errobj->as_string; # OR "$errobj";
78               my $error_list    = $errobj->as_array;  # ordered list of what when wrong
79               my $error_hash    = $errobj->as_hash;   # hash of arrayrefs of errors
80           } else {
81               # form passed validation
82           }
83
84           ### will add an error for any form key not found in $val_hash
85           my $vob = CGI::Ex::Validate->new({no_extra_keys => 1});
86           my $errobj = $vob->validate($form, $val_hash);
87

DESCRIPTION

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.
93
94       It also has full support for providing the same validation in
95       javascript.  It provides methods for attaching the javascript to exist‐
96       ing forms.
97
98       As opposed to other kitchen sync validation modules, CGI::Ex::Validate
99       offers the simple types of validation, and makes it easy to add your
100       own custom types.
101

METHODS

103       "new"
104           Used to instantiate the object.  Arguments are either a hash, or
105           hashref, or nothing at all.  Keys of the hash become the keys of
106           the object.
107
108       "get_validation"
109           Given a filename or YAML string will return perl hash.  If more
110           than one group is contained in the file, it will return an arrayref
111           of hashrefs.
112
113               my $ref = $self->get_validation($file);
114
115       "get_validation_keys"
116           Given a filename or YAML string or a validation hashref, will
117           return all of the possible keys found in the validation hash.  This
118           can be used to check to see if extra items have been passed to val‐
119           idate.  If a second argument contains a form hash is passed,
120           get_validation_keys will only return the keys of groups that were
121           validated.
122
123               my $key_hashref = $self->get_validation_keys($val_hash);
124
125           The values of the hash are the names of the fields.
126
127       "validate"
128           Arguments are a form hashref or cgi object, a validation hashref or
129           filename, and an optional what_was_validated arrayref (discussed
130           further later on).  If a CGI object is passed, CGI::Ex::get_form
131           will be called on that object to turn it into a hashref.  If a
132           filename is given for the validation, get_validation will be called
133           on that filename.  If the what_was_validated_arrayref is passed -
134           it will be populated (pushed) with the field hashes that were actu‐
135           ally validated (anything that was skipped because of validate_if
136           will not be in the array).
137
138           If the form passes validation, validate will return undef.  If it
139           fails validation, it will return a CGI::Ex::Validate::Error object.
140           If the 'raise_error' option has been set, validate will die with a
141           CGI::Ex::validate::Error object as the value.
142
143               my $err_obj = $self->validate($form, $val_hash);
144
145               # OR #
146
147               $self->{raise_error} = 1; # can also be listed in the val_hash
148               eval { $self->validate($form, $val_hash) };
149               if ($@) { my $err_obj = $@; }
150
151       "generate_js"
152           Works with CGI::Ex::JSONDump, but can also work with  JSON or YAML
153           if desired (see JSON or YAML).
154
155           Takes a validation hash, a form name, and an optional javascript
156           uri path and returns Javascript that can be embedded on a page and
157           will perform identical validations as the server side.  The form
158           name must be the name of the form that the validation will act upon
159           - the name is used to register an onsubmit function.  The
160           javascript uri path is used to embed the locations of javascript
161           source files included with the CGI::Ex distribution.
162
163           The javascript uri path is highly dependent upon the server config‐
164           uration and therefore must be configured manually.  It may be
165           passed to generate_js, or it may be specified in $JS_URI_PATH.
166           There are two files included with this module that are needed -
167           CGI/Ex/yaml_load.js and CGI/Ex/validate.js.  When generating the js
168           code, generate_js will look in $JS_URI_PATH_YAML and
169           $JS_URI_PATH_VALIDATE.  If either of these are not set, generate_js
170           will default to "$JS_URI_PATH/CGI/Ex/yaml_load.js" and
171           "$JS_URI_PATH/CGI/Ex/validate.js" (Note: yaml_load is only needed
172           if the flags no_jsondump and no_json have been set).
173
174               $self->generate_js($val_hash, 'my_form', "/cgi-bin/js")
175
176               # would generate something like the following...
177
178               <script src="/cgi-bin/js/CGI/Ex/validate.js"></script>
179               ... more js follows ...
180
181               $CGI::Ex::Validate::JS_URI_PATH = "/stock/js";
182               $self->generate_js($val_hash, 'my_form')
183
184               # would generate something like the following...
185
186               <script src="/stock/js/CGI/Ex/validate.js"></script>
187               ... more js follows ...
188
189           Referencing yaml_load.js and validate.js can be done in any of sev‐
190           eral ways.  They can be copied to or symlinked to a fixed location
191           in the server's html directory.  They can also be printed out by a
192           cgi.  The method "->print_js" has been provided in CGI::Ex for
193           printing js files found in the perl hierarchy.  See CGI::Ex for
194           more details.  The $JS_URI_PATH of "/cgi-bin/js" could contain the
195           following:
196
197               #!/usr/bin/perl -w
198
199               use strict;
200               use CGI::Ex;
201
202               ### path_info should contain something like /CGI/Ex/yaml_load.js
203               my $info = $ENV{PATH_INFO} ⎪⎪ '';
204               die "Invalid path" if $info !~ m⎪^(/\w+)+.js$⎪;
205               $info =~ s⎪^/+⎪⎪;
206
207               CGI::Ex->new->print_js($info);
208               exit;
209
210           The print_js method in CGI::Ex is designed to cache the javascript
211           in the browser (caching is suggested as they are medium sized
212           files).
213
214       "->cgix"
215           Returns a CGI::Ex object.  Used internally.
216

VALIDATION HASH

218       The validation hash may be passed as a hashref or as a filename, or as
219       a YAML document string.  If it is a filename, it will be translated
220       into a hash using the %EXT_HANDLER for the extension on the file.  If
221       there is no extension, it will use $DEFAULT_EXT as a default.
222       CGI::Ex::Conf is used for the reading of files.
223
224       Keys matching the regex m/^(general⎪group)\s+(\w+)$/ are reserved and
225       are counted as GROUP OPTIONS.  Other keys (if any, should be field
226       names that need validation).
227
228       If the GROUP OPTION 'group validate_if' is set, the validation will
229       only be validated if the conditions are met.  If 'group validate_if' is
230       not specified, then the validation will proceed.
231
232       Each of the items listed in the validation will be validated.  The val‐
233       idation order is determined in one of three ways:
234
235       Specify 'group fields' arrayref.
236               # order will be (username, password, 'm/\w+_foo/', somethingelse)
237               {
238                 'group title' => "User Information",
239                 'group fields' => [
240                   {field => 'username',   required => 1},
241                   {field => 'password',   required => 1},
242                   {field => 'm/\w+_foo/', required => 1},
243                 ],
244                 somethingelse => {required => 1},
245               }
246
247       Specify 'group order' arrayref.
248               # order will be (username, password, 'm/\w+_foo/', somethingelse)
249               {
250                 'group title' => "User Information",
251                 'group order' => [qw(username password), 'm/\w+_foo/'],
252                 username      => {required => 1},
253                 password      => {required => 1},
254                 'm/\w+_foo/'  => {required => 1},
255                 somethingelse => {required => 1},
256               }
257
258       Do nothing - use sorted order.
259               # order will be ('m/\w+_foo/', password, somethingelse, username)
260               {
261                 'group title' => "User Information",
262                 username      => {required => 1},
263                 password      => {required => 1},
264                 'm/\w+_foo/'  => {required => 1},
265                 somethingelse => {required => 1},
266               }
267
268       Optionally the 'group fields' or the 'group order' may contain the word
269       'OR' as a special keyword.  If the item preceding 'OR' fails validation
270       the item after 'OR' will be tested instead.  If the item preceding 'OR'
271       passes validation the item after 'OR' will not be tested.
272
273           'group order' => [qw(zip OR postalcode state OR region)],
274
275       Each individual field validation hashref will operate on the field con‐
276       tained in the 'field' key.  This key may also be a regular expression
277       in the form of 'm/somepattern/'.  If a regular expression is used, all
278       keys matching that pattern will be validated.  If the field key is not
279       specified, the key from the top level hash will be used.
280
281           foobar => {   # "foobar" is not used as key because field is specified
282              field    => 'real_key_name',
283              required => 1,
284           },
285           real_key_name2 => {
286              required => 1,
287           },
288
289       Each of the individual field validation hashrefs should contain the
290       types listed in VALIDATION TYPES.
291

VALIDATION TYPES

293       This section lists the available validation types.  Multiple instances
294       of the same type may be used for some validation types by adding a num‐
295       ber to the type (ie match, match2, match232, match_94).  Multiple
296       instances are validated in sorted order.  Types that allow multiple
297       values are:
298
299           compare
300           custom
301           equals
302           match
303           max_in_set
304           min_in_set
305           replace
306           required_if
307           sql
308           type
309           validate_if
310
311       "validate_if"
312           If validate_if is specified, the field will only be validated if
313           the conditions are met.  Works in JS.
314
315               validate_if => {field => 'name', required => 1, max_len => 30}
316               # Will only validate if the field "name" is present and is less than 30 chars.
317
318               validate_if => 'name',
319               # SAME as
320               validate_if => {field => 'name', required => 1},
321
322               validate_if => '! name',
323               # SAME as
324               validate_if => {field => 'name', max_in_set => '0 of name'},
325
326               validate_if => {field => 'country', compare => "eq US"},
327               # only if country's value is equal to US
328
329               validate_if => {field => 'country', compare => "ne US"},
330               # if country doesn't equal US
331
332               validate_if => {field => 'password', match => 'm/^md5\([a-z0-9]{20}\)$/'},
333               # if password looks like md5(12345678901234567890)
334
335               {
336                 field       => 'm/^(\w+)_pass/',
337                 validate_if => '$1_user',
338                 required    => 1,
339               }
340               # will validate foo_pass only if foo_user was present.
341
342           The validate_if may also contain an arrayref of validation items.
343           So that multiple checks can be run.  They will be run in order.
344           validate_if will return true only if all options returned true.
345
346               validate_if => ['email', 'phone', 'fax']
347
348           Optionally, if validate_if is an arrayref, it may contain the word
349           'OR' as a special keyword.  If the item preceding 'OR' fails vali‐
350           dation the item after 'OR' will be tested instead.  If the item
351           preceding 'OR' passes validation the item after 'OR' will not be
352           tested.
353
354               validate_if => [qw(zip OR postalcode)],
355
356       "required_if"
357           Requires the form field if the condition is satisfied.  The condi‐
358           tions available are the same as for validate_if.  This is somewhat
359           the same as saying:
360
361               validate_if => 'some_condition',
362               required    => 1
363
364               required_if => 'some_condition',
365
366           If a regex is used for the field name, the required_if field will
367           have any match patterns swapped in.
368
369               {
370                 field       => 'm/^(\w+)_pass/',
371                 required_if => '$1_user',
372               }
373
374           This example would require the "foobar_pass" field to be set if the
375           "foobar_user" field was passed.
376
377       "required"
378           Requires the form field to have some value.  If the field is not
379           present, no other checks will be run.
380
381       "min_values" and "max_values"
382           Allows for specifying the maximum number of form elements passed.
383           max_values defaults to 1 (You must explicitly set it higher to
384           allow more than one item by any given name).
385
386       "min_in_set" and "max_in_set"
387           Somewhat like min_values and max_values except that you specify the
388           fields that participate in the count.  Also - entries that are not
389           defined or do not have length are not counted.  An optional "of"
390           can be placed after the number for human readability.
391
392               min_in_set => "2 of foo bar baz",
393                 # two of the fields foo, bar or baz must be set
394                 # same as
395               min_in_set => "2 foo bar baz",
396                 # same as
397               min_in_set => "2 OF foo bar baz",
398
399               validate_if => {field => 'whatever', max_in_set => '0 of whatever'},
400                 # only run validation if there were zero occurrences of whatever
401
402       "enum"
403           Allows for checking whether an item matches a set of options.  In
404           perl the value may be passed as an arrayref.  In the conf or in
405           perl the value may be passed of the options joined with ⎪⎪.
406
407               {
408                 field => 'password_type',
409                 enum  => 'plaintext⎪⎪crypt⎪⎪md5', # OR enum => [qw(plaintext crypt md5)],
410               }
411
412       "equals"
413           Allows for comparison of two form elements.  Can have an optional
414           !.
415
416               {
417                 field  => 'password',
418                 equals => 'password_verify',
419               },
420               {
421                 field  => 'domain1',
422                 equals => '!domain2', # make sure the fields are not the same
423               }
424
425       "min_len and max_len"
426           Allows for check on the length of fields
427
428               {
429                 field   => 'site',
430                 min_len => 4,
431                 max_len => 100,
432               }
433
434       "match"
435           Allows for regular expression comparison.  Multiple matches may be
436           concatenated with ⎪⎪.  Available in JS.
437
438               {
439                 field   => 'my_ip',
440                 match   => 'm/^\d{1,3}(\.\d{1,3})3$/',
441                 match_2 => '!/^0\./ ⎪⎪ !/^192\./',
442               }
443
444       "compare"
445           Allows for custom comparisons.  Available types are >, <, >=, <=,
446           !=, ==, gt, lt, ge, le, ne, and eq.  Comparisons also work in the
447           JS.
448
449               {
450                 field    => 'my_number',
451                 match    => 'm/^\d+$/',
452                 compare1 => '> 100',
453                 compare2 => '< 255',
454                 compare3 => '!= 150',
455               }
456
457       "sql"
458           SQL query based - not available in JS.  The database handle will be
459           looked for in the value $self->{dbhs}->{foo} if sql_db_type is set
460           to 'foo', otherwise it will default to $self->{dbh}.  If
461           $self->{dbhs}->{foo} or $self->{dbh} is a coderef - they will be
462           called and should return a dbh.
463
464               {
465                 field => 'username',
466                 sql   => 'SELECT COUNT(*) FROM users WHERE username = ?',
467                 sql_error_if => 1, # default is 1 - set to 0 to negate result
468                 # sql_db_type  => 'foo', # will look for a dbh under $self->{dbhs}->{foo}
469               }
470
471       "custom"
472           Custom value - not available in JS.  Allows for extra programming
473           types.  May be either a boolean value predetermined before calling
474           validate, or may be a coderef that will be called during valida‐
475           tion.  If coderef is called, it will be passed the field name, the
476           form value for that name, and a reference to the field validation
477           hash.  If the custom type returns false the element fails valida‐
478           tion and an error is added.
479
480               {
481                 field => 'username',
482                 custom => sub {
483                   my ($key, $val, $type, $field_val_hash) = @_;
484                   # do something here
485                   return 0;
486                 },
487               }
488
489       "custom_js"
490           Custom value - only available in JS.  Allows for extra programming
491           types.  May be either a boolean value pre-determined before calling
492           validate, or may be section of javascript that will be eval'ed.
493           The last value (return value) of the eval'ed javascript will deter‐
494           mine if validation passed.  A false value indicates the value did
495           not pass validation.  A true value indicates that it did.  See the
496           t/samples/js_validate_3.html page for a sample of usage.
497
498               {
499                 field => 'date',
500                 required => 1,
501                 match    => 'm⎪^\d\d\d\d/\d\d/\d\d$⎪',
502                 match_error => 'Please enter date in YYYY/MM/DD format',
503                 custom_js => "
504                   var t=new Date();
505                   var y=t.getYear()+1900;
506                   var m=t.getMonth() + 1;
507                   var d=t.getDate();
508                   if (m<10) m = '0'+m;
509                   if (d<10) d = '0'+d;
510                   (value > ''+y+'/'+m+'/'+d) ? 1 : 0;
511                 ",
512                 custom_js_error => 'The date was not greater than today.',
513               }
514
515       "type"
516           Allows for more strict type checking.  Currently supported types
517           include CC (credit card).  Other types will be added upon request
518           provided we can add a perl and a javascript version.
519
520               {
521                 field => 'credit_card',
522                 type  => 'CC',
523               }
524

SPECIAL VALIDATION TYPES

526       "field"
527           Specify which field to work on.  Key may be a regex in the form
528           'm/\w+_user/'.  This key is required if 'group fields' is used or
529           if validate_if or required_if are used.  It can optionally be used
530           with other types to specify a different form element to operate on.
531           On errors, if a non-default error is found, $field will be swapped
532           with the value found in field.
533
534           The field name may also be a regular expression in the form of
535           'm/somepattern/'.  If a regular expression is used, all keys match‐
536           ing that pattern will be validated.
537
538       "name"
539           Name to use for errors.  If a name is not specified, default errors
540           will use "The field $field" as the name.  If a non-default error is
541           found, $name will be swapped with this name.
542
543       "delegate_error"
544           This option allows for any errors generated on a field to delegate
545           to a different field.  If the field name was a regex, any patterns
546           will be swapped into the delegate_error value. This option is gen‐
547           erally only useful with the as_hash method of the error object (for
548           inline errors).
549
550               {
551                 field => 'zip',
552                 match => 'm/^\d{5}/',
553               },
554               {
555                 field => 'zip_plus4',
556                 match => 'm/^\d{4}/',
557                 delegate_error => 'zip',
558               },
559               {
560                 field => 'm/^(id_[\d+])_user$/',
561                 delegate_error => '$1',
562               },
563
564       "exclude_js"
565           This allows the cgi to do checking while keeping the checks from
566           being run in JavaScript
567
568               {
569                 field      => 'cgi_var',
570                 required   => 1,
571                 exclude_js => 1,
572               }
573
574       "exclude_cgi"
575           This allows the js to do checking while keeping the checks from
576           being run in the cgi
577
578               {
579                 field       => 'js_var',
580                 required    => 1,
581                 exclude_cgi => 1,
582               }
583

MODIFYING VALIDATION TYPES

585       The following types will modify the form value before it is processed.
586       They work in both the perl and in javascript as well.  The javascript
587       version changes the actual value in the form on appropriate form types.
588
589       "do_not_trim"
590           By default, validate will trim leading and trailing whitespace from
591           submitted values.  Set do_not_trim to 1 to allow it to not trim.
592
593               {field => 'foo', do_not_trim => 1}
594
595       "trim_control_chars"
596           Off by default.  If set to true, removes characters in the \x00 to
597           \x31 range (Tabs are translated to a single space).
598
599               {field => 'foo', trim_control_chars => 1}
600
601       "replace"
602           Pass a swap pattern to change the actual value of the form.  Any
603           perl regex can be passed but it is suggested that javascript com‐
604           patible regexes are used to make generate_js possible.
605
606               {field => 'foo', replace => 's/(\d{3})(\d{3})(\d{3})/($1) $2-$3/'}
607
608       "default"
609           Set item to default value if there is no existing value (undefined
610           or zero length string).
611
612               {field => 'country', default => 'EN'}
613
614       "to_upper_case" and "to_lower_case"
615           Do what they say they do.
616
617       "untaint"
618           Requires that the validated field has been also checked with an
619           enum, equals, match, compare, custom, or type check.  If the field
620           has been checked and there are no errors - the field is
621           "untainted."
622
623           This is for use in conjunction with perl's -T switch.
624
625       "clear_on_error"
626           Clears the form field should a validation error occur.  Only sup‐
627           ported on the Javascript side (no affect on the server side).
628

ERROR OBJECT

630       Failed validation results in an error an error object created via the
631       new_error method.  The default error class is CGI::Ex::Validate::Error.
632
633       The error object has several methods for determining what the errors
634       were.
635
636       "as_array"
637           Returns an array or arrayref (depending on scalar context) of
638           errors that occurred in the order that they occurred.  Individual
639           groups may have a heading and the entire validation will have a
640           heading (the default heading can be changed via the
641           'as_array_title' group option).  Each error that occurred is a sep‐
642           arate item and are pre-pended with 'as_array_prefix' (which is a
643           group option - default is '  ').  The as_array_ options may also be
644           set via a hashref passed to as_array.  as_array_title defaults to
645           'Please correct the following items:'.
646
647             ### if this returns the following
648             my $array = $err_obj->as_array;
649             # $array looks like
650             # ['Please correct the following items:', '  error1', '  error2']
651
652             ### then this would return the following
653             my $array = $err_obj->as_array({
654               as_array_prefix => '  - ',
655               as_array_title  => 'Something went wrong:',
656             });
657             # $array looks like
658             # ['Something went wrong:', '  - error1', '  - error2']
659
660       "as_string"
661           Returns values of as_array joined with a newline.  This method is
662           used as the stringification for the error object.  Values of
663           as_array are joined with 'as_string_join' which defaults to "\n".
664           If 'as_string_header' is set, it will be pre-pended onto the error
665           string.  If 'as_string_footer' is set, it will be appended onto the
666           error string.
667
668             ### if this returns the following
669             my $string = $err_obj->as_string;
670             # $string looks like
671             # "Please correct the following items:\n  error1\n  error2"
672
673             ### then this would return the following
674             my $string = $err_obj->as_string({
675               as_array_prefix  => '  - ',
676               as_array_title   => 'Something went wrong:',
677               as_string_join   => '<br />',
678               as_string_header => '<span class="error">',
679               as_string_footer => '</span>',
680             });
681             # $string looks like
682             # '<span class="error">Something went wrong:<br />  - error1<br />  - error2</span>'
683
684       "as_hash"
685           Returns a hash or hashref (depending on scalar context) of errors
686           that occurred.  Each key is the field name of the form that failed
687           validation with 'as_hash_suffix' added on as a suffix.
688           as_hash_suffix is available as a group option and may also be
689           passed in via a hashref as the only argument to as_hash.  The
690           default value is '_error'.  The values of the hash are arrayrefs of
691           errors that occurred to that form element.
692
693           By default as_hash will return the values of the hash as arrayrefs
694           (a list of the errors that occurred to that key).  It is possible
695           to also return the values as strings.  Three options are available
696           for formatting: 'as_hash_header' which will be pre-pended onto the
697           error string, 'as_hash_footer' which will be appended, and
698           'as_hash_join' which will be used to join the arrayref.  The only
699           argument required to force the stringification is 'as_hash_join'.
700
701             ### if this returns the following
702             my $hash = $err_obj->as_hash;
703             # $hash looks like
704             # {key1_error => ['error1', 'error2']}
705
706             ### then this would return the following
707             my $hash = $err_obj->as_hash({
708               as_hash_suffix => '_foo',
709               as_hash_join   => '<br />',
710               as_hash_header => '<span class="error">'
711               as_hash_footer => '</span>'
712             });
713             # $hash looks like
714             # {key1_foo => '<span class="error">error1<br />error2</span>'}
715

GROUP OPTIONS

717       Any key in a validation hash matching the pattern m/^(group⎪gen‐
718       eral)\s+(\w+)$/ is considered a group option (the reason that either
719       group or general may be used is that CGI::Ex::Validate used to have the
720       concept of validation groups - these were not commonly used so support
721       has been deprecated as of the 2.10 release).  Group options will also
722       be looked for in the Validate object ($self) and can be set when
723       instantiating the object ($self->{raise_error} is equivalent to $val‐
724       hash->{'group raise_error'}).  The current know options are:
725
726       Options may also be set globally before calling validate by populating
727       the %DEFAULT_OPTIONS global hash.
728
729       "title"
730           Used as a group section heading when as_array or as_string is
731           called by the error object.
732
733               'group title' => 'Title of errors',
734
735       "order"
736           Order in which to validate key/value pairs of group.
737
738               'group order' => [qw(user pass email OR phone)],
739
740       "fields"
741           Arrayref of validation items to validate.
742
743               'group fields' => [{
744                   field    => 'field1',
745                   required => 1,
746               }, {
747                   field    => 'field2',
748                   required => 1,
749               }],
750
751       "validate_if"
752           If specified - the entire hashref will only be validated if the
753           "if" conditions are met.
754
755               'group validate_if => {field => 'email', required => 1},
756
757           This group would only validate all fields if the email field was
758           present.
759
760       "raise_error"
761           If raise_error is true, any call to validate that fails validation
762           will die with an error object as the value.
763
764       "no_extra_fields"
765           If no_extra_fields is true, validate will add errors for any field
766           found in form that does not have a field_val hashref in the valida‐
767           tion hash.  Default is false.  If no_extra_fields is set to 'used',
768           it will check for any keys that were not in a group that was vali‐
769           dated.
770
771           An important exception to this is that field_val hashrefs or field
772           names listed in a validate_if or required_if statement will not be
773           included.  You must have an explicit entry for each key.
774
775       "\w+_error"
776           These items allow for an override of the default errors.
777
778             'group required_error' => '$name is really required',
779             'group max_len_error'  => '$name must be shorter than $value characters',
780               # OR #
781             my $self = CGI::Ex::Validate->new({
782               max_len_error => '$name must be shorter than $value characters',
783             });
784
785       "as_array_title"
786           Used as the section title for all errors that occur, when as_array
787           or as_string is called by the error object.
788
789       "as_array_prefix"
790           Used as prefix to individual errors that occur, when as_array or
791           as_string is called by the error object.  Each individual error
792           will be prefixed with this string.  Headings will not be prefixed.
793           Default is '  '.
794
795       "as_string_join"
796           When as_string is called, the values from as_array will be joined
797           with as_string_join.  Default value is "\n".
798
799       "as_string_header"
800           If set, will be pre-pended onto the string when as_string is
801           called.
802
803       "as_string_footer"
804           If set, will be pre-pended onto the string when as_string is
805           called.
806
807       "as_hash_suffix"
808           Added on to key names during the call to as_hash.  Default is
809           '_error'.
810
811       "as_hash_join"
812           By default, as_hash will return hashref values that are errors
813           joined with the default as_hash_join value of <br />.  It can also
814           return values that are arrayrefs of the errors.  This can be done
815           by setting as_hash_join to a non-true value (for example '')
816
817       "as_hash_header"
818           If as_hash_join has been set to a true value, as_hash_header may be
819           set to a string that will be pre-pended on to the error string.
820
821       "as_hash_footer"
822           If as_hash_join has been set to a true value, as_hash_footer may be
823           set to a string that will be postpended on to the error string.
824
825       "no_inline"
826           If set to true, the javascript validation will not attempt to gen‐
827           erate inline errors.  Default is true.  Inline errors are indepen‐
828           dent of confirm and alert errors.
829
830               'general no_inline' => 1,
831
832       "no_confirm"
833           If set to true, the javascript validation will try to use an alert
834           instead of a confirm to inform the user of errors.  Alert and con‐
835           firm are independent or inline errors.  Default is false.
836
837               'general no_confirm' => 1,
838
839       "no_alert"
840           If set to true, the javascript validation will not show an alert
841           box when errors occur.  Default is false.  This option only comes
842           into play if no_confirm is also set.  This option is independent of
843           inline errors.  Although it is possible to turn off all errors by
844           setting no_inline, no_confirm, and no_alert all to 1, it is sug‐
845           gested that at least one of the error reporting facilities is left
846           on.
847
848               'general no_alert' => 1,
849

JAVASCRIPT

851       CGI::Ex::Validate provides for having duplicate validation on the
852       client side as on the server side.  Errors can be shown in any combina‐
853       tion of inline and confirm, inline and alert, inline only, confirm
854       only, alert only, and none.  These combinations are controlled by the
855       group options no_inline, no_confirm, and no_alert.  Javascript valida‐
856       tion can be generated for a page using the "->generate_js" Method of
857       CGI::Ex::Validate.  It is also possible to store the validation inline
858       with the html.  This can be done by giving each of the elements to be
859       validated an attribute called "validation", or by setting a global
860       javascript variable called "document.validation" or "var validation".
861       An html file containing this validation will be read in using
862       CGI::Ex::Conf::read_handler_html.
863
864       All inline html validation must be written in yaml.
865
866       It is anticipated that the html will contain something like either of
867       the following examples:
868
869         <script src="/cgi-bin/js/CGI/Ex/yaml_load.js"></script>
870         <script src="/cgi-bin/js/CGI/Ex/validate.js"></script>
871         <script>
872         // \n\ allows all browsers to view this as a single string
873         document.validation = "\n\
874         general no_confirm: 1\n\
875         general no_alert: 1\n\
876         group order: [username, password]\n\
877         username:\n\
878           required: 1\n\
879           max_len: 20\n\
880         password:\n\
881           required: 1\n\
882           max_len: 30\n\
883         ";
884         if (document.check_form) document.check_form('my_form_name');
885         </script>
886
887       Alternately we can use element attributes:
888
889         <form name="my_form_name">
890
891         Username: <input type=text size=20 name=username validation="
892           required: 1
893           max_len: 20
894         "><br>
895         <span class=error id=username_error>[% username_error %]</span><br>
896
897         Password: <input type=text size=20 name=password validation="
898           required: 1
899           max_len: 30
900         "><br>
901         <span class=error id=password_error>[% password_error %]</span><br>
902
903         <input type=submit>
904
905         </form>
906
907         <script src="/cgi-bin/js/CGI/Ex/yaml_load.js"></script>
908         <script src="/cgi-bin/js/CGI/Ex/validate.js"></script>
909         <script>
910         if (document.check_form) document.check_form('my_form_name');
911         </script>
912
913       The read_handler_html from CGI::Ex::Conf will find either of these
914       types of validation.
915
916       If inline errors are asked for, each error that occurs will attempt to
917       find an html element with its name as the id.  For example, if the
918       field "username" failed validation and created a "username_error", the
919       javascript would set the html of <span id="username_error"></span> to
920       the error message.
921
922       It is suggested to use something like the following so that you can
923       have inline javascript validation as well as report validation errors
924       from the server side as well.
925
926          <span class=error id=password_error>[% password_error %]</span><br>
927
928       If the javascript fails for some reason, the form should still be able
929       to submit as normal (fail gracefully).
930
931       If the confirm option is used, the errors will be displayed to the
932       user.  If they choose OK they will be able to try and fix the errors.
933       If they choose cancel, the form will submit anyway and will rely on the
934       server to do the validation.  This is for fail safety to make sure that
935       if the javascript didn't validate correctly, the user can still submit
936       the data.
937

THANKS

939       Thanks to Eamon Daly for providing bug fixes for bugs in validate.js
940       caused by HTML::Prototype.
941

LICENSE

943       This module may be distributed under the same terms as Perl itself.
944

AUTHOR

946       Paul Seamons <perl at seamons dot com>
947
948
949
950perl v5.8.8                       2007-10-18              CGI::Ex::Validate(3)
Impressum