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