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

NAME

6       CGI::Ex::Validate - The "Just Right" form validator with 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
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

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 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

METHODS

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

VALIDATION HASH

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           'm/\w+/' => { # this will apply to all fields matching this regex
313               required => 1,
314           },
315
316       Each of the individual field validation hashrefs should contain the
317       types listed in VALIDATION TYPES.
318

VALIDATION TYPES

320       This section lists the available validation types.  Multiple instances
321       of the same type may be used for some validation types by adding a
322       number to the type (ie match, match2, match232).  Multiple instances
323       are validated in sorted order.  Types that allow multiple values are:
324       compare, custom, custom_js, equals, match, required_if, sql,
325       validate_if, and replace (replace is a MODIFICATION TYPE).
326
327       "compare"
328           Allows for custom comparisons.  Available types are >, <, >=, <=,
329           !=, ==, gt, lt, ge, le, ne, and eq.  Comparisons also work in the
330           JS.
331
332               {
333                   field    => 'my_number',
334                   match    => 'm/^\d+$/',
335                   compare1 => '> 100',
336                   compare2 => '< 255',
337                   compare3 => '!= 150',
338               }
339
340       "custom"
341           Custom value - not available in JS.  Allows for extra programming
342           types.  May be either a boolean value predetermined before calling
343           validate, or may be a coderef that will be called during
344           validation.  If coderef is called, it will be passed the field
345           name, the form value for that name, and a reference to the field
346           validation hash.  If the custom type returns false the element
347           fails validation and an error is added.
348
349               {
350                   field => 'username',
351                   custom => sub {
352                       my ($key, $val, $field_val_hash, $checktype, $form) = @_;
353                       # do something here
354                       return 0;
355                   },
356                   custom_error => '$name was not valid',
357               }
358
359           Often it is desirable to specify a different message depending upon
360           the code passed to custom.  To use a custom error message simply
361           die with the error message.  Note that you will want to add a
362           newline or else perl will add the line number and file for you -
363           CGI::Ex::Validate will remove the trailing newline.
364
365               {
366                   field => 'username',
367                   custom => sub {
368                       my ($key, $val) = @_;
369                       die "Custom error message 1\n" if $val eq '1';
370                       die "Custom error message 2\n" if $val eq '2';
371                       return 0;
372                   },
373                   custom_error => '$name default custom error message',
374               }
375
376       "custom_js"
377           Custom value - only available in JS.  Allows for extra programming
378           types.  May be a javascript function (if fully declared in
379           javascript), a string containing a javascript function (that will
380           be eval'ed into a real function), a boolean value pre-determined
381           before calling validate, or may be section of javascript that will
382           be eval'ed (the last value of the eval'ed javascript will determine
383           if validation passed).  A false response indicates the value did
384           not pass validation.  A true response indicates that it did.  See
385           the samples/validate_js_0_tests.html page for a sample of usages.
386
387               {
388                   field => 'date',
389                   required => 1,
390                   match    => 'm|^\d\d\d\d/\d\d/\d\d$|',
391                   match_error => 'Please enter date in YYYY/MM/DD format',
392                   custom_js => "function (args) {
393                       var t = new Date();
394                       var y = t.getYear()+1900;
395                       var m = t.getMonth() + 1;
396                       var d = t.getDate();
397                       if (m < 10) m = '0'+m;
398                       if (d < 10) d = '0'+d;
399                       (args.value > ''+y+'/'+m+'/'+d) ? 1 : 0;
400                   }",
401                   custom_js_error => 'The date was not greater than today.',
402               }
403
404           Often it is desirable to specify a different message depending upon
405           the function passed to custom_js.  To use a custom error message
406           simply throw the error message.
407
408               {
409                   field => 'username',
410                   custom_js => 'function (args) {
411                       if (args.value == 1) throw "Custom error message 1";
412                       if (args.value == 2) throw "Custom error message 2";
413                       return 0;
414                   }',
415                   custom_js_error => '$name default custom error message',
416               }
417
418       "enum"
419           Allows for checking whether an item matches a set of options.  In
420           perl the value may be passed as an arrayref.  In the conf or in
421           perl the value may be passed of the options joined with ||.
422
423               {
424                   field => 'password_type',
425                   enum  => 'plaintext||crypt||md5', # OR enum => [qw(plaintext crypt md5)],
426               }
427
428       "equals"
429           Allows for comparison of two form elements.  Can have an optional
430           !.
431
432               {
433                   field  => 'password',
434                   equals => 'password_verify',
435               },
436               {
437                   field  => 'domain1',
438                   equals => '!domain2', # make sure the fields are not the same
439               }
440
441       "had_error"
442           Typically used by a validate_if.  Allows for checking if this item
443           has had an error.
444
445               {
446                   field => 'alt_password',
447                   validate_if => {field => 'password', had_error => 1},
448               }
449
450           This is basically the opposite of was_valid.
451
452       "match"
453           Allows for regular expression comparison.  Multiple matches may be
454           concatenated with ||.  Available in JS.
455
456               {
457                   field   => 'my_ip',
458                   match   => 'm/^\d{1,3}(\.\d{1,3})3$/',
459                   match_2 => '!m/^0\./ || !m/^192\./',
460               }
461
462       "max_in_set" and "min_in_set"
463           Somewhat like min_values and max_values except that you specify the
464           fields that participate in the count.  Also - entries that are not
465           defined or do not have length are not counted.  An optional "of"
466           can be placed after the number for human readability.
467
468               min_in_set => "2 of foo bar baz",
469                 # two of the fields foo, bar or baz must be set
470                 # same as
471               min_in_set => "2 foo bar baz",
472                 # same as
473               min_in_set => "2 OF foo bar baz",
474
475               validate_if => {field => 'whatever', max_in_set => '0 of whatever'},
476                 # only run validation if there were zero occurrences of whatever
477
478       "max_len and min_len"
479           Allows for check on the length of fields
480
481               {
482                   field   => 'site',
483                   min_len => 4,
484                   max_len => 100,
485               }
486
487       "max_values" and "min_values"
488           Allows for specifying the maximum number of form elements passed.
489           max_values defaults to 1 (You must explicitly set it higher to
490           allow more than one item by any given name).
491
492       "required"
493           Requires the form field to have some value.  If the field is not
494           present, no other checks will be run and an error will be given.
495
496           It has been common for code to try "required =" 0> which
497           essentially has no effect - instead use "validate_if ="
498           'fieldname', required => 1>.  This results in the fieldname only
499           being required if the fieldname is present.
500
501       "required_if"
502           Requires the form field if the condition is satisfied.  The
503           conditions available are the same as for validate_if.  This is
504           somewhat the same as saying:
505
506               validate_if => 'some_condition',
507               required    => 1
508
509               required_if => 'some_condition',
510
511           It is different in that other checks will run - whereas validate_if
512           skips all validation if some condition is not met.
513
514           If a regex is used for the field name, the required_if field will
515           have any match patterns swapped in.
516
517               {
518                   field       => 'm/^(\w+)_pass/',
519                   required_if => '$1_user',
520               }
521
522           This example would require the "foobar_pass" field to be set if the
523           "foobar_user" field was passed.
524
525       "sql"
526           SQL query based - not available in JS.  The database handle will be
527           looked for in the value $self->{dbhs}->{foo} if sql_db_type is set
528           to 'foo', otherwise it will default to $self->{dbh}.  If
529           $self->{dbhs}->{foo} or $self->{dbh} is a coderef - they will be
530           called and should return a dbh.
531
532               {
533                   field => 'username',
534                   sql   => 'SELECT COUNT(*) FROM users WHERE username = ?',
535                   sql_error_if => 1, # default is 1 - set to 0 to negate result
536                   # sql_db_type  => 'foo', # will look for a dbh under $self->{dbhs}->{foo}
537               }
538
539       "type"
540           Allows for more strict type checking.  Currently supported types
541           include CC (credit card), EMAIL, DOMAIN, IP, URL, INT, UINT, and
542           NUM.  Other types will be added upon request provided we can add a
543           perl and a javascript version (extra types often aren't necessary
544           as the custom and custom_js options give arbitrary checking).  If a
545           type checks fails - other compare, custom, or length checks will
546           not be ran.
547
548               {
549                   field => 'credit_card',
550                   type  => 'CC',
551               }
552
553           "CC"
554               Simple Luhn-10 check.  Note that spaces and dashes are left in
555               place.
556
557           "EMAIL"
558               Very basic check to see if the value looks like an address.
559               The local part must only contain [\w.~!\#\$%\^&*\-=+?] and the
560               domain must be a domain or ip.  If you want full fledged RFC
561               compliant checking consider something like:
562
563                   {
564                       field => 'email',
565                       custom => sub {
566                           my ($key, $val, $fv, $type, $form) = @_;
567                           require Mail::Address;
568                           my @a = Mail::Address->parse($val);
569                           die "Invalid address\n" if @a != 1;
570                           return $form->{$key} = $a[0]->address;
571                        },
572                    }
573
574           "DOMAIN"
575               Checks for a valid domain name - does no lookup of the domain.
576               For that use a custom sub.
577
578           "IP"
579               Basic IPv4 check.
580
581           "URL"
582               Basic check that string matches something resembling an http or
583               https url.
584
585           "INT"
586               Checks for an integer between -2147483648 and 2147483648
587
588           "UINT"
589               Checks for an unsigned integer between 0 and 4294967295.
590
591           "NUM"
592               Checks for something that looks like a number.  Scientic
593               notation is not allowed.  No range enforced.
594
595       "validate_if"
596           If validate_if is specified, the field will only be validated if
597           the conditions are met.  Works in JS.
598
599               validate_if => {field => 'name', required => 1, max_len => 30}
600               # Will only validate if the field "name" is present and is less than 30 chars.
601
602               validate_if => 'name',
603               # SAME as
604               validate_if => {field => 'name', required => 1},
605
606               validate_if => '! name',
607               # SAME as
608               validate_if => {field => 'name', max_in_set => '0 of name'},
609
610               validate_if => 'name was_valid',
611               # SAME as
612               validate_if => {field => 'name', was_valid => 1},
613
614               validate_if => {field => 'country', compare => "eq US"},
615               # only if country's value is equal to US
616
617               validate_if => {field => 'country', compare => "ne US"},
618               # if country doesn't equal US
619
620               validate_if => {field => 'password', match => 'm/^md5\([a-z0-9]{20}\)$/'},
621               # if password looks like md5(12345678901234567890)
622
623               {
624                   field       => 'm/^(\w+)_pass/',
625                   validate_if => '$1_user',
626                   required    => 1,
627               },
628               {
629                   field       => 'm/^(\w+)_pass2/',
630                   validate_if => '$1_pass',
631                   equals      => '$1_pass',
632                   required    => 1,
633               }
634
635               # will validate foo_pass only if foo_user was present.
636
637           The validate_if may also contain an arrayref of validation items.
638           So that multiple checks can be run.  They will be run in order.
639           validate_if will return true only if all options returned true.
640
641               validate_if => ['email', 'phone', 'fax']
642
643           Optionally, if validate_if is an arrayref, it may contain the word
644           'OR' as a special keyword.  If the item preceding 'OR' fails
645           validation the item after 'OR' will be tested instead.  If the item
646           preceding 'OR' passes validation the item after 'OR' will not be
647           tested.
648
649               validate_if => [qw(zip OR postalcode)],
650
651       "was_valid"
652           Typically used by a validate_if.  Allows for checking if this item
653           has successfully been validated.
654
655               {
656                   field => 'password2',
657                   validate_if => {field => 'password', was_valid => 1},
658               }
659
660           This is basically the opposite of had_error.
661

SPECIAL VALIDATION TYPES

663       "field"
664           Specify which field to work on.  Key may be a regex in the form
665           'm/\w+_user/'.  This key is required in a hashref passed to 'group
666           order'.  It can optionally be used with other types to specify a
667           different form element to operate on.  On errors, if a non-default
668           error is found, $field will be swapped with the value found in
669           field.
670
671           The field name may also be a regular expression in the form of
672           'm/somepattern/'.  If a regular expression is used, all keys
673           matching that pattern will be validated.
674
675       "name"
676           Name to use for errors.  If a name is not specified, default errors
677           will use "The field $field" as the name.  If a non-default error is
678           found, $name will be swapped with this name.
679
680       "delegate_error"
681           This option allows for any errors generated on a field to delegate
682           to a different field.  If the field name was a regex, any patterns
683           will be swapped into the delegate_error value. This option is
684           generally only useful with the as_hash method of the error object
685           (for inline errors).
686
687               {
688                   field => 'zip',
689                   match => 'm/^\d{5}/',
690               },
691               {
692                   field => 'zip_plus4',
693                   match => 'm/^\d{4}/',
694                   delegate_error => 'zip',
695               },
696               {
697                   field => 'm/^(id_[\d+])_user$/',
698                   delegate_error => '$1',
699               },
700
701       "exclude_js"
702           This allows the cgi to do checking while keeping the checks from
703           being run in JavaScript
704
705               {
706                   field      => 'cgi_var',
707                   required   => 1,
708                   exclude_js => 1,
709               }
710
711       "exclude_cgi"
712           This allows the js to do checking while keeping the checks from
713           being run in the cgi
714
715               {
716                   field       => 'js_var',
717                   required    => 1,
718                   exclude_cgi => 1,
719               }
720
721       "vif_disable"
722           Only functions in javascript.  Will mark set the form element to
723           disabled if validate_if fails.  It will mark it as enabled if
724           validate_if is successful.  This item should normally only be used
725           when onevent includes "change" or "blur".
726

MODIFYING VALIDATION TYPES

728       The following types will modify the form value before it is processed.
729       They work in both the perl and in javascript as well.  The javascript
730       version changes the actual value in the form on appropriate form types.
731
732       "do_not_trim"
733           By default, validate will trim leading and trailing whitespace from
734           submitted values.  Set do_not_trim to 1 to allow it to not trim.
735
736               {field => 'foo', do_not_trim => 1}
737
738       "trim_control_chars"
739           Off by default.  If set to true, removes characters in the \x00 to
740           \x31 range (Tabs are translated to a single space).
741
742               {field => 'foo', trim_control_chars => 1}
743
744       "replace"
745           Pass a swap pattern to change the actual value of the form.  Any
746           perl regex can be passed but it is suggested that javascript
747           compatible regexes are used to make generate_js possible.
748
749               {field => 'foo', replace => 's/(\d{3})(\d{3})(\d{3})/($1) $2-$3/'}
750
751       "default"
752           Set item to default value if there is no existing value (undefined
753           or zero length string).
754
755               {field => 'country', default => 'EN'}
756
757       "to_upper_case" and "to_lower_case"
758           Do what they say they do.
759
760       "untaint"
761           Requires that the validated field has been also checked with an
762           enum, equals, match, compare, custom, or type check.  If the field
763           has been checked and there are no errors - the field is
764           "untainted."
765
766           This is for use in conjunction with perl's -T switch.
767
768       "clear_on_error"
769           Clears the form field should a validation error occur.  Only
770           supported on the Javascript side (no affect on the server side).
771

ERROR OBJECT

773       Failed validation results in an error an error object created via the
774       new_error method.  The default error class is CGI::Ex::Validate::Error.
775
776       The error object has several methods for determining what the errors
777       were.
778
779       "as_array"
780           Returns an array or arrayref (depending on scalar context) of
781           errors that occurred in the order that they occurred.  Individual
782           groups may have a heading and the entire validation will have a
783           heading (the default heading can be changed via the
784           'as_array_title' group option).  Each error that occurred is a
785           separate item and are pre-pended with 'as_array_prefix' (which is a
786           group option - default is '  ').  The as_array_ options may also be
787           set via a hashref passed to as_array.  as_array_title defaults to
788           'Please correct the following items:'.
789
790               # if this returns the following
791               my $array = $err_obj->as_array;
792               # $array looks like
793               # ['Please correct the following items:', '  error1', '  error2']
794
795               # then this would return the following
796               my $array = $err_obj->as_array({
797                   as_array_prefix => '  - ',
798                   as_array_title  => 'Something went wrong:',
799               });
800               # $array looks like
801               # ['Something went wrong:', '  - error1', '  - error2']
802
803       "as_string"
804           Returns values of as_array joined with a newline.  This method is
805           used as the stringification for the error object.  Values of
806           as_array are joined with 'as_string_join' which defaults to "\n".
807           If 'as_string_header' is set, it will be pre-pended onto the error
808           string.  If 'as_string_footer' is set, it will be appended onto the
809           error string.
810
811               # if this returns the following
812               my $string = $err_obj->as_string;
813               # $string looks like
814               # "Please correct the following items:\n  error1\n  error2"
815
816               # then this would return the following
817               my $string = $err_obj->as_string({
818                   as_array_prefix  => '  - ',
819                   as_array_title   => 'Something went wrong:',
820                   as_string_join   => '<br />',
821                   as_string_header => '<span class="error">',
822                   as_string_footer => '</span>',
823               });
824               # $string looks like
825               # '<span class="error">Something went wrong:<br />  - error1<br />  - error2</span>'
826
827       "as_hash"
828           Returns a hash or hashref (depending on scalar context) of errors
829           that occurred.  Each key is the field name of the form that failed
830           validation with 'as_hash_suffix' added on as a suffix.
831           as_hash_suffix is available as a group option and may also be
832           passed in via a hashref as the only argument to as_hash.  The
833           default value is '_error'.  The values of the hash are arrayrefs of
834           errors that occurred to that form element.
835
836           By default as_hash will return the values of the hash as arrayrefs
837           (a list of the errors that occurred to that key).  It is possible
838           to also return the values as strings.  Three options are available
839           for formatting: 'as_hash_header' which will be pre-pended onto the
840           error string, 'as_hash_footer' which will be appended, and
841           'as_hash_join' which will be used to join the arrayref.  The only
842           argument required to force the stringification is 'as_hash_join'.
843
844               # if this returns the following
845               my $hash = $err_obj->as_hash;
846               # $hash looks like
847               # {key1_error => ['error1', 'error2']}
848
849               # then this would return the following
850               my $hash = $err_obj->as_hash({
851                   as_hash_suffix => '_foo',
852                   as_hash_join   => '<br />',
853                   as_hash_header => '<span class="error">'
854                   as_hash_footer => '</span>'
855               });
856               # $hash looks like
857               # {key1_foo => '<span class="error">error1<br />error2</span>'}
858

GROUP OPTIONS

860       Any key in a validation hash matching the pattern m/^group \s+ (\w+)$/x
861       is considered a group option (the reason that either group or general
862       may be used is that CGI::Ex::Validate used to have the concept of
863       validation groups - these were not commonly used so support has been
864       removed as of the 2.10 release).  (the old name of 'general' vs 'group'
865       is still supported but deprecated)
866
867       "title"
868           Used as a group section heading when as_array or as_string is
869           called by the error object.
870
871               'group title' => 'Title of errors',
872
873       "order"
874           Order in which to validate key/value pairs of group.
875
876               'group order' => [qw(user pass email OR phone)],
877
878               # OR
879
880               'group order' => [{
881                   field    => 'field1',
882                   required => 1,
883               }, {
884                   field    => 'field2',
885                   required => 1,
886               }],
887
888       "fields"
889           Alias for 'group order'.
890
891       "validate_if"
892           If specified - the entire hashref will only be validated if the
893           "if" conditions are met.
894
895               'group validate_if => {field => 'email', required => 1},
896
897           This group would only validate all fields if the email field was
898           present.
899
900       "raise_error"
901           If raise_error is true, any call to validate that fails validation
902           will die with an error object as the value.
903
904       "no_extra_fields"
905           If no_extra_fields is true, validate will add errors for any field
906           found in form that does not have a field_val hashref in the
907           validation hash.  Default is false.  If no_extra_fields is set to
908           'used', it will check for any keys that were not in a group that
909           was validated.
910
911           An important exception to this is that field_val hashrefs or field
912           names listed in a validate_if or required_if statement will not be
913           included.  You must have an explicit entry for each key.
914
915       "\w+_error"
916           These items allow for an override of the default errors.
917
918               'group required_error' => '$name is really required',
919               'group max_len_error'  => '$name must be shorter than $value characters',
920                 # OR #
921               my $self = CGI::Ex::Validate->new({
922                   max_len_error => '$name must be shorter than $value characters',
923               });
924
925       "as_array_title"
926           Used as the section title for all errors that occur, when as_array
927           or as_string is called by the error object.
928
929       "as_array_prefix"
930           Used as prefix to individual errors that occur, when as_array or
931           as_string is called by the error object.  Each individual error
932           will be prefixed with this string.  Headings will not be prefixed.
933           Default is '  '.
934
935       "as_string_join"
936           When as_string is called, the values from as_array will be joined
937           with as_string_join.  Default value is "\n".
938
939       "as_string_header"
940           If set, will be pre-pended onto the string when as_string is
941           called.
942
943       "as_string_footer"
944           If set, will be pre-pended onto the string when as_string is
945           called.
946
947       "as_hash_suffix"
948           Added on to key names during the call to as_hash.  Default is
949           '_error'.
950
951       "as_hash_join"
952           By default, as_hash will return hashref values that are errors
953           joined with the default as_hash_join value of <br />.  It can also
954           return values that are arrayrefs of the errors.  This can be done
955           by setting as_hash_join to a non-true value (for example '')
956
957       "as_hash_header"
958           If as_hash_join has been set to a true value, as_hash_header may be
959           set to a string that will be pre-pended on to the error string.
960
961       "as_hash_footer"
962           If as_hash_join has been set to a true value, as_hash_footer may be
963           set to a string that will be postpended on to the error string.
964
965       "onevent"
966           Defaults to {submit => 1}.  This controls when the javascript
967           validation will take place.  May be passed any or all or load,
968           submit, change, or blur.  Multiple events may be passed in the
969           hash.
970
971               'group onevent' => {submit => 1, change => 1}',
972
973           A comma separated string of types may also be passed:
974
975               'group onevent' => 'submit,change,blur,load',
976
977           Currently, change and blur will not work for dynamically matched
978           field names such as 'm/\w+/'.  Support will be added.
979
980       "set_hook"
981           Defaults document.validate_set_hook which defaults to nothing.  If
982           "group set_hook" or document.validate_set_hook are set to a
983           function, they will be passed the key name of a form element that
984           had a validation error and the error that will be set.  If a true
985           value is returned, then validate will not also the inline error.
986           If no value or false is returned (default) the validate will
987           continue setting the inline error.  This gives full control over
988           setting inline errors. samples/validate_js_2_onchange.html has a
989           good example of using these hooks.
990
991               'group set_hook' => "function (args) {
992                   alert("Setting error to field "+args.key);
993               }",
994
995           The args parameter includes key, value, val_hash, and form.
996
997           The document.validate_set_hook option is probably the better option
998           to use, as it helps to separate display functionality out into your
999           html templates rather than storing too much html logic in your CGI.
1000
1001       "clear_hook"
1002           Similar to set_hook, but called when inline error is cleared.  Its
1003           corresponding default is document.validate_clear_hook.  The clear
1004           hook is also sampled in samples/validate_js_2_onchange.html
1005
1006               'group clear_hook' => "function (args) {
1007                   alert("Clear error on field "+args.key);
1008               }",
1009
1010           The args parameter includes key, val_hash, form, and was_valid.
1011
1012       "no_inline"
1013           If set to true, the javascript validation will not attempt to
1014           generate inline errors when the only "group onevent" type is
1015           "submit".  Default is true.  Inline errors are independent of
1016           confirm and alert errors.
1017
1018               'group no_inline' => 1,
1019
1020       "no_confirm"
1021           If set to true, the javascript validation will try to use an alert
1022           instead of a confirm to inform the user of errors when one of the
1023           "group onevent" types is "submit".  Alert and confirm are
1024           independent or inline errors.  Default is false.
1025
1026               'group no_confirm' => 1,
1027
1028       "no_alert"
1029           If set to true, the javascript validation will not show an alert
1030           box when errors occur.  Default is false.  This option only comes
1031           into play if no_confirm is also set.  This option is only in effect
1032           if "group onevent" includes "submit".  This option is independent
1033           of inline errors.  Although it is possible to turn off all errors
1034           by setting no_inline, no_confirm, and no_alert all to 1, it is
1035           suggested that at least one of the error reporting facilities is
1036           left on.
1037
1038               'group no_alert' => 1,
1039

JAVASCRIPT

1041       CGI::Ex::Validate provides for having duplicate validation on the
1042       client side as on the server side.  Errors can be shown in any
1043       combination of inline and confirm, inline and alert, inline only,
1044       confirm only, alert only, and none.  These combinations are controlled
1045       by the group options no_inline, no_confirm, and no_alert.  Javascript
1046       validation can be generated for a page using the "->generate_js" method
1047       of CGI::Ex::Validate.
1048
1049       (Note: It is also possible to store the validation inline with the html
1050       as YAML and have it read in using the HTML conf handler - but this
1051       feature has been deprecated - see the included html samples for how to
1052       do this).
1053
1054       Generate JS will create something similar to the following (based on
1055       your validation):
1056
1057           <script src="/cgi-bin/js/CGI/Ex/validate.js"></script>
1058           <script>
1059           document.validation = {
1060             'group no_confirm': 1,
1061             'group no_alert':   1,
1062             'group onevent':    'change,blur,submit',
1063             'group order': ['username', 'password'],
1064             username: {
1065               required: 1,
1066               max_len: 20
1067             },
1068             password: {
1069               required: 1,
1070               max_len: 30
1071             }
1072           };
1073           if (document.check_form) document.check_form('my_form_name');
1074           </script>
1075
1076       If inline errors are enabled (default), each error that occurs will
1077       attempt to find an html element with its name as the id.  For example,
1078       if the field "username" failed validation and created a
1079       "username_error", the javascript would set the html of <span
1080       id="username_error"></span> to the error message.
1081
1082       It is suggested to use something like the following so that you can
1083       have inline javascript validation as well as report validation errors
1084       from the server side as well.
1085
1086          <span class=error id=password_error>[% password_error %]</span><br>
1087
1088       If the javascript fails for some reason, the form should still be able
1089       to submit as normal (fail gracefully).
1090
1091       Additionally, there are two hooks that are called when ever an inline
1092       error is set or cleared.  The following hooks are used in
1093       samples/validate_js_2_onchange.html to highlight the row and set an
1094       icon.
1095
1096           document.validate_set_hook = function (args) {
1097             document.getElementById(args.key+'_img').innerHTML
1098               = '<span style="font-weight:bold;color:red">!</span>';
1099             document.getElementById(args.key+'_row').style.background
1100               = '#ffdddd';
1101           };
1102
1103           document.validate_clear_hook = function (args) {
1104             if (args.was_valid) {
1105               document.getElementById(args.key+'_img').innerHTML
1106                   = '<span style="font-weight:bold;color:green">+</span>';
1107               document.getElementById(args.key+'_row').style.background
1108                   = '#ddffdd';
1109             } else {
1110               document.getElementById(args.key+'_img').innerHTML = '';
1111               document.getElementById(args.key+'_row').style.background = '#fff';
1112             }
1113           };
1114
1115       If you have jquery that looks like:
1116
1117           document.validate_set_hook = function (args) {
1118             $('#'+args.key+'_img').html('<span style="font-weight:bold;color:red">!</span>');
1119             $('#'+args.key+'_row').css('backgroundColor', '#ffdddd');
1120           };
1121
1122           document.validate_clear_hook = function (args) {
1123             if (args.was_valid) {
1124               $('#'+args.key+'_img').html('<span style="font-weight:bold;color:green">+</span>');
1125               $('#'+args.key+'_row').css('backgroundColor', '#ddffdd');
1126             } else {
1127               $('#'+args.key+'_img').html('');
1128               $('#'+args.key+'_row').css('backgroundColor', '#fff');
1129             }
1130           };
1131
1132       These hooks can also be set as "group clear_hook" and "group set_hook"
1133           which are defined further above.
1134
1135           If the confirm option is used ("group onevent" includes submit and
1136           "group no_confirm" is false), the errors will be displayed to the
1137           user.  If they choose OK they will be able to try and fix the errors.
1138           If they choose cancel, the form will submit anyway and will rely on
1139           the server to do the validation.  This is for fail safety to make sure
1140           that if the javascript didn't validate correctly, the user can still
1141       submit the data.
1142

LICENSE

1144       This module may be distributed under the same terms as Perl itself.
1145

AUTHOR

1147       Paul Seamons <perl at seamons dot com>
1148
1149
1150
1151perl v5.28.1                      2018-12-07              CGI::Ex::Validate(3)
Impressum