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

VERSION

10       version 2.54
11

SYNOPSIS

13       use CGI::Ex::Validate;
14
15           # THE SHORT
16
17           my $errobj = CGI::Ex::Validate->new->validate($form, $val_hash);
18
19           # THE LONG
20
21           my $form = CGI->new;
22           # OR #
23           my $form = CGI::Ex->new; # OR CGI::Ex->get_form;
24           # OR #
25           my $form = {key1 => 'val1', key2 => 'val2'};
26
27
28           # simplest
29           my $val_hash = {
30               'group order' => [qw(username email email2)],
31               username => {
32                   required => 1,
33                   max_len  => 30,
34                   field    => 'username',
35                   # field is optional in this case - will use key name
36               },
37               email    => {
38                   required => 1,
39                   max_len  => 100,
40                   type     => 'email',
41               },
42               email2   => {
43                   equals   => 'email',
44               },
45           };
46
47           # ordered
48           my $val_hash = {
49               'group order' => [{
50                   field    => 'username', # field is not optional in this case
51                   required => 1,
52                   max_len  => 30,
53               }, {
54                   field    => 'email',
55                   required => 1,
56                   max_len  => 100,
57               }, {
58                   field    => 'email2',
59                   equals   => 'email',
60               }],
61           };
62
63
64           my $vob    = CGI::Ex::Validate->new;
65           my $errobj = $vob->validate($form, $val_hash);
66           if ($errobj) {
67               # get errors back in any of several useful ways
68               my $error_heading = $errobj->as_string; # OR "$errobj";
69               my $error_list    = $errobj->as_array;  # ordered list of what when wrong
70               my $error_hash    = $errobj->as_hash;   # hash of arrayrefs of errors
71           } else {
72               # the form passed validation
73           }
74
75
76           my $js_uri_path = '/js/';     # static or dynamic URI path to find CGI/Ex/validate.js
77           my $form_name   = "the_form"; # name of the form to attach javascript to
78
79           # generate javascript to validate an existing form
80           my $javascript = $vob->generate_js($val_hash, {
81               form_name   => $form_name,
82               js_uri_path => $js_uri_path,
83           });
84
85           # OR let Validate create the form and javascript for you
86           my $form = $vob->generate_form($val_hash, {
87               form_name   => $form_name,   # will use a random name if not passed
88               js_uri_path => $js_uri_path,
89           });
90

DESCRIPTION

92       CGI::Ex::Validate is one of many validation modules.  It aims to have
93       all of the basic data validation functions, avoid adding all of the
94       millions of possible types, while still giving the capability for the
95       developer to add their own types for the rare cases that the basic ones
96       don't suffice.  Generally anything more than basic validation probably
97       needs programmatic or data based validation.
98
99       CGI::Ex::Validate also has full support for providing the same
100       validation in javascript.  It provides methods for attaching the
101       javascript to existing forms.  This ability is tightly integrated into
102       CGI::Ex::App, but it should be easy to add validation just about
103       anywhere using any type of controller.
104
105       As opposed to other kitchen sync validation modules, CGI::Ex::Validate
106       offers the simple types of validation, and makes it easy to add your
107       own custom types.  Asside from custom and custom_js, all validation
108       markup is declarative.
109

METHODS

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

VALIDATION HASH

232       The validation hash may be passed as a hashref or as a filename, or as
233       a YAML document string.  Experience has shown it to be better
234       programming to pass in a hashref.  If the validation "hash" is a
235       filename or a YAML string, it will be translated into a hash using
236       CGI::Ex::Conf.
237
238       Keys matching the regex m/^group \s+ (\w+)$/x such as "group onevent"
239       are reserved and are counted as GROUP OPTIONS.  Other keys (if any,
240       should be field names that need validation).
241
242       If the GROUP OPTION 'group validate_if' is set, the validation will
243       only be validated if the conditions of the validate_if are met.  If
244       'group validate_if' is not specified, then the validation will proceed.
245       See the validate_if VALIDATION type for more information.
246
247       Each of the items listed in the validation will be validated.  The
248       validation order is determined the following ways:
249
250       Specify 'group order' arrayref with hashrefs.
251               # order will be (username, password, 'm/\w+_foo/', somethingelse)
252               {
253                   'group title' => "User Information",
254                   'group order' => [
255                       {field => 'username',   required => 1},
256                       {field => 'password',   required => 1},
257                       {field => 'm/\w+_foo/', required => 1},
258                   ],
259                   somethingelse => {required => 1},
260                   }
261
262       Specify 'group order' arrayref with field key names.
263               # order will be (username, password, 'm/\w+_foo/', somethingelse)
264               {
265                   'group title' => "User Information",
266                   'group order' => [qw(username password), 'm/\w+_foo/'],
267                   username      => {required => 1},
268                   password      => {required => 1},
269                   'm/\w+_foo/'  => {required => 1},
270                   somethingelse => {required => 1},
271               }
272
273       Do nothing - use sorted order.
274               # order will be ('m/\w+_foo/', password, somethingelse, username)
275               {
276                   'group title' => "User Information",
277                   username      => {required => 1},
278                   password      => {required => 1},
279                   'm/\w+_foo/'  => {required => 1},
280                   somethingelse => {required => 1},
281               }
282
283       Optionally the 'group order' may contain the word 'OR' as a special
284       keyword.  If the item preceding 'OR' fails validation the item after
285       'OR' will be tested instead.  If the item preceding 'OR' passes
286       validation the item after 'OR' will not be tested.
287
288           'group order' => [qw(zip OR postalcode state OR region)],
289
290       At this time, only "group onevent" submit works with this option.
291       Using OR is not needed if testing for one or more values -- instead you
292       should use min_in_set or max_in_set (OR is still useful for other
293       cases).
294
295           'zip' => {
296             max_in_set: '1 of zip, postalcode',
297           },
298           'state' => {
299             max_in_set: '1 of state, region',
300           },
301
302       Each individual field validation hashref will operate on the field
303       contained in the 'field' key.  This key may also be a regular
304       expression in the form of 'm/somepattern/'.  If a regular expression is
305       used, all keys matching that pattern will be validated.  If the field
306       key is not specified, the key from the top level hash will be used.
307
308           foobar => {   # "foobar" is not used as key because field is specified
309               field    => 'real_key_name',
310               required => 1,
311           },
312           real_key_name2 => {
313               required => 1,
314           },
315           'm/\w+/' => { # this will apply to all fields matching this regex
316               required => 1,
317           },
318
319       Each of the individual field validation hashrefs should contain the
320       types listed in VALIDATION TYPES.
321

VALIDATION TYPES

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

SPECIAL VALIDATION TYPES

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

MODIFYING VALIDATION TYPES

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

ERROR OBJECT

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

GROUP OPTIONS

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

JAVASCRIPT

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

LICENSE

1147       This module may be distributed under the same terms as Perl itself.
1148

AUTHOR

1150       Paul Seamons <perl at seamons dot com>
1151
1152
1153
1154perl v5.36.0                      2022-07-22              CGI::Ex::Validate(3)
Impressum