3 CGI::Ex::Validate - The "Just Right" form validator with javascript in parallel
11 my $errobj = CGI::Ex::Validate->new->validate($form, $val_hash);
17 my $form = CGI::Ex->new; # OR CGI::Ex->get_form;
19 my $form = {key1 => 'val1', key2 => 'val2'};
24 'group order' => [qw(username email email2)],
29 # field is optional in this case - will use key name
44 field => 'username', # field is not optional in this case
58 my $vob = CGI::Ex::Validate->new;
59 my $errobj = $vob->validate($form, $val_hash);
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
66 # the form passed validation
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
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,
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,
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.
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.
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.
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.
115 =item C<get_validation>
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.
120 =item C<get_validation_keys>
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.
128 my $key_hashref = $self->get_validation_keys($val_hash);
130 The keys of the hash are the names of the fields.
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
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.
149 my $err_obj = $self->validate($form, $val_hash);
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 = $@; }
157 =item C<generate_form>
159 Takes a validation hash, and additional arguments and generates an HTML form suitable
160 for inclusion in a web based application.
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
169 Works with CGI::Ex::JSONDump.
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.
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".
187 my $js = $self->generate_js($val_hash, 'my_form', "/cgi-bin/js")
189 my $js = $self->generate_js($val_hash, {
190 form_name => 'my_form',
191 js_uri_path => '/cgi-bin/js',
194 # would generate something like the following...
196 <script src="/cgi-bin/js/CGI/Ex/validate.js"></script>
197 ... more js follows ...
199 $CGI::Ex::Validate::JS_URI_PATH = "/stock/js";
200 $self->generate_js($val_hash, 'my_form')
202 # would generate something like the following...
204 <script src="/stock/js/CGI/Ex/validate.js"></script>
205 ... more js follows ...
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:
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$|;
224 CGI::Ex->new->print_js($info);
227 The print_js method in CGI::Ex is designed to cache the javascript in
232 Returns a CGI::Ex object. Used internally if a CGI object is
233 passed to validate rather than a straight form hash.
237 =head1 VALIDATION HASH
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
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).
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.
254 Each of the items listed in the validation will be validated. The
255 validation order is determined the following ways:
259 =item Specify 'group order' arrayref with hashrefs.
261 # order will be (username, password, 'm/\w+_foo/', somethingelse)
263 'group title' => "User Information",
265 {field => 'username', required => 1},
266 {field => 'password', required => 1},
267 {field => 'm/\w+_foo/', required => 1},
269 somethingelse => {required => 1},
272 =item Specify 'group order' arrayref with field key names.
274 # order will be (username, password, 'm/\w+_foo/', somethingelse)
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},
284 =item Do nothing - use sorted order.
286 # order will be ('m/\w+_foo/', password, somethingelse, username)
288 'group title' => "User Information",
289 username => {required => 1},
290 password => {required => 1},
291 'm/\w+_foo/' => {required => 1},
292 somethingelse => {required => 1},
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.
302 'group order' => [qw(zip OR postalcode state OR region)],
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).
309 max_in_set: '1 of zip, postalcode',
312 max_in_set: '1 of state, region',
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.
321 foobar => { # "foobar" is not used as key because field is specified
322 field => 'real_key_name',
329 Each of the individual field validation hashrefs should contain the
330 types listed in VALIDATION TYPES.
332 =head1 VALIDATION TYPES
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, enum, match, required_if, sql,
339 type, validate_if, and replace (replace is a MODIFICATION TYPE).
345 Allows for custom comparisons. Available types are
346 >, <, >=, <=, !=, ==, gt, lt, ge, le, ne, and eq. Comparisons
350 field => 'my_number',
354 compare3 => '!= 150',
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.
369 my ($key, $val, $type, $field_val_hash) = @_;
377 Custom value - only available in JS. Allows for extra programming types.
378 May be a javascript function (if fully declared in javascript), a string containing
379 a javascript function (that will be eval'ed into a real function),
380 a boolean value pre-determined before calling validate, or may be
381 section of javascript that will be eval'ed (the last value of
382 the eval'ed javascript will determine if validation passed). A false response indicates
383 the value did not pass validation. A true response indicates that it did. See
384 the samples/validate_js_0_tests.html page for a sample of usages.
389 match => 'm|^\d\d\d\d/\d\d/\d\d$|',
390 match_error => 'Please enter date in YYYY/MM/DD format',
391 custom_js => "function (args) {
393 var y=t.getYear()+1900;
394 var m=t.getMonth() + 1;
398 (args.value > ''+y+'/'+m+'/'+d) ? 1 : 0;
400 custom_js_error => 'The date was not greater than today.',
405 Allows for checking whether an item matches a set of options. In perl
406 the value may be passed as an arrayref. In the conf or in perl the
407 value may be passed of the options joined with ||.
410 field => 'password_type',
411 enum => 'plaintext||crypt||md5', # OR enum => [qw(plaintext crypt md5)],
416 Allows for comparison of two form elements. Can have an optional !.
420 equals => 'password_verify',
424 equals => '!domain2', # make sure the fields are not the same
429 Typically used by a validate_if. Allows for checking if this item has had
433 field => 'alt_password',
434 validate_if => {field => 'password', had_error => 1},
437 This is basically the opposite of was_valid.
441 Allows for regular expression comparison. Multiple matches may
442 be concatenated with ||. Available in JS.
446 match => 'm/^\d{1,3}(\.\d{1,3})3$/',
447 match_2 => '!/^0\./ || !/^192\./',
450 =item C<max_in_set> and C<min_in_set>
452 Somewhat like min_values and max_values except that you specify the
453 fields that participate in the count. Also - entries that are not
454 defined or do not have length are not counted. An optional "of" can
455 be placed after the number for human readability.
457 min_in_set => "2 of foo bar baz",
458 # two of the fields foo, bar or baz must be set
460 min_in_set => "2 foo bar baz",
462 min_in_set => "2 OF foo bar baz",
464 validate_if => {field => 'whatever', max_in_set => '0 of whatever'},
465 # only run validation if there were zero occurrences of whatever
467 =item C<max_len and min_len>
469 Allows for check on the length of fields
477 =item C<max_values> and C<min_values>
479 Allows for specifying the maximum number of form elements passed.
480 max_values defaults to 1 (You must explicitly set it higher
481 to allow more than one item by any given name).
485 Requires the form field to have some value. If the field is not present,
486 no other checks will be run.
490 Requires the form field if the condition is satisfied. The conditions
491 available are the same as for validate_if. This is somewhat the same
494 validate_if => 'some_condition',
497 required_if => 'some_condition',
499 If a regex is used for the field name, the required_if
500 field will have any match patterns swapped in.
503 field => 'm/^(\w+)_pass/',
504 required_if => '$1_user',
507 This example would require the "foobar_pass" field to be set
508 if the "foobar_user" field was passed.
512 SQL query based - not available in JS. The database handle will be looked
513 for in the value $self->{dbhs}->{foo} if sql_db_type is set to 'foo',
514 otherwise it will default to $self->{dbh}. If $self->{dbhs}->{foo} or
515 $self->{dbh} is a coderef - they will be called and should return a dbh.
519 sql => 'SELECT COUNT(*) FROM users WHERE username = ?',
520 sql_error_if => 1, # default is 1 - set to 0 to negate result
521 # sql_db_type => 'foo', # will look for a dbh under $self->{dbhs}->{foo}
526 Allows for more strict type checking. Currently supported types
527 include CC (credit card), EMAIL, DOMAIN, IP, URL. Other types will be
528 added upon request provided we can add a perl and a javascript
532 field => 'credit_card',
538 If validate_if is specified, the field will only be validated
539 if the conditions are met. Works in JS.
541 validate_if => {field => 'name', required => 1, max_len => 30}
542 # Will only validate if the field "name" is present and is less than 30 chars.
544 validate_if => 'name',
546 validate_if => {field => 'name', required => 1},
548 validate_if => '! name',
550 validate_if => {field => 'name', max_in_set => '0 of name'},
552 validate_if => 'name was_valid',
554 validate_if => {field => 'name', was_valid => 1},
556 validate_if => {field => 'country', compare => "eq US"},
557 # only if country's value is equal to US
559 validate_if => {field => 'country', compare => "ne US"},
560 # if country doesn't equal US
562 validate_if => {field => 'password', match => 'm/^md5\([a-z0-9]{20}\)$/'},
563 # if password looks like md5(12345678901234567890)
566 field => 'm/^(\w+)_pass/',
567 validate_if => '$1_user',
570 # will validate foo_pass only if foo_user was present.
572 The validate_if may also contain an arrayref of validation items. So that
573 multiple checks can be run. They will be run in order. validate_if will
574 return true only if all options returned true.
576 validate_if => ['email', 'phone', 'fax']
578 Optionally, if validate_if is an arrayref, it may contain the word
579 'OR' as a special keyword. If the item preceding 'OR' fails validation
580 the item after 'OR' will be tested instead. If the item preceding 'OR'
581 passes validation the item after 'OR' will not be tested.
583 validate_if => [qw(zip OR postalcode)],
587 Typically used by a validate_if. Allows for checking if this item has successfully
591 field => 'password2',
592 validate_if => {field => 'password', was_valid => 1},
595 This is basically the opposite of had_error.
599 =head1 SPECIAL VALIDATION TYPES
605 Specify which field to work on. Key may be a regex in the form
606 'm/\w+_user/'. This key is required in a hashref passed to 'group
607 order'. It can optionally be used with other types to specify a
608 different form element to operate on. On errors, if a non-default
609 error is found, $field will be swapped with the value found in field.
611 The field name may also be a regular expression in the
612 form of 'm/somepattern/'. If a regular expression is used, all keys
613 matching that pattern will be validated.
617 Name to use for errors. If a name is not specified, default errors will use
618 "The field $field" as the name. If a non-default error is found, $name
619 will be swapped with this name.
621 =item C<delegate_error>
623 This option allows for any errors generated on a field to delegate to
624 a different field. If the field name was a regex, any patterns will
625 be swapped into the delegate_error value. This option is generally only
626 useful with the as_hash method of the error object (for inline errors).
630 match => 'm/^\d{5}/',
633 field => 'zip_plus4',
634 match => 'm/^\d{4}/',
635 delegate_error => 'zip',
638 field => 'm/^(id_[\d+])_user$/',
639 delegate_error => '$1',
644 This allows the cgi to do checking while keeping the checks from
645 being run in JavaScript
655 This allows the js to do checking while keeping the checks from
666 Only functions in javascript. Will mark set the form element to
667 disabled if validate_if fails. It will mark it as enabled if
668 validate_if is successful. This item should normally only be used
669 when onevent includes "change" or "blur".
673 =head1 MODIFYING VALIDATION TYPES
675 The following types will modify the form value before it is processed.
676 They work in both the perl and in javascript as well. The javascript
677 version changes the actual value in the form on appropriate form types.
683 By default, validate will trim leading and trailing whitespace
684 from submitted values. Set do_not_trim to 1 to allow it to
687 {field => 'foo', do_not_trim => 1}
689 =item C<trim_control_chars>
691 Off by default. If set to true, removes characters in the
692 \x00 to \x31 range (Tabs are translated to a single space).
694 {field => 'foo', trim_control_chars => 1}
698 Pass a swap pattern to change the actual value of the form.
699 Any perl regex can be passed but it is suggested that javascript
700 compatible regexes are used to make generate_js possible.
702 {field => 'foo', replace => 's/(\d{3})(\d{3})(\d{3})/($1) $2-$3/'}
706 Set item to default value if there is no existing value (undefined
707 or zero length string).
709 {field => 'country', default => 'EN'}
711 =item C<to_upper_case> and C<to_lower_case>
713 Do what they say they do.
717 Requires that the validated field has been also checked with
718 an enum, equals, match, compare, custom, or type check. If the
719 field has been checked and there are no errors - the field is "untainted."
721 This is for use in conjunction with perl's -T switch.
723 =item C<clear_on_error>
725 Clears the form field should a validation error occur. Only supported
726 on the Javascript side (no affect on the server side).
732 Failed validation results in an error an error object created via the
733 new_error method. The default error class is CGI::Ex::Validate::Error.
735 The error object has several methods for determining what the errors were.
741 Returns an array or arrayref (depending on scalar context) of errors that
742 occurred in the order that they occurred. Individual groups may have a heading
743 and the entire validation will have a heading (the default heading can be changed
744 via the 'as_array_title' group option). Each error that occurred is a separate
745 item and are pre-pended with 'as_array_prefix' (which is a group option - default
746 is ' '). The as_array_ options may also be set via a hashref passed to as_array.
747 as_array_title defaults to 'Please correct the following items:'.
749 # if this returns the following
750 my $array = $err_obj->as_array;
752 # ['Please correct the following items:', ' error1', ' error2']
754 # then this would return the following
755 my $array = $err_obj->as_array({
756 as_array_prefix => ' - ',
757 as_array_title => 'Something went wrong:',
760 # ['Something went wrong:', ' - error1', ' - error2']
764 Returns values of as_array joined with a newline. This method is used as
765 the stringification for the error object. Values of as_array are joined with
766 'as_string_join' which defaults to "\n". If 'as_string_header' is set, it will
767 be pre-pended onto the error string. If 'as_string_footer' is set, it will be
768 appended onto the error string.
770 # if this returns the following
771 my $string = $err_obj->as_string;
773 # "Please correct the following items:\n error1\n error2"
775 # then this would return the following
776 my $string = $err_obj->as_string({
777 as_array_prefix => ' - ',
778 as_array_title => 'Something went wrong:',
779 as_string_join => '<br />',
780 as_string_header => '<span class="error">',
781 as_string_footer => '</span>',
784 # '<span class="error">Something went wrong:<br /> - error1<br /> - error2</span>'
788 Returns a hash or hashref (depending on scalar context) of errors that
789 occurred. Each key is the field name of the form that failed
790 validation with 'as_hash_suffix' added on as a suffix. as_hash_suffix
791 is available as a group option and may also be passed in via a
792 hashref as the only argument to as_hash. The default value is
793 '_error'. The values of the hash are arrayrefs of errors that
794 occurred to that form element.
796 By default as_hash will return the values of the hash as arrayrefs (a
797 list of the errors that occurred to that key). It is possible to also
798 return the values as strings. Three options are available for
799 formatting: 'as_hash_header' which will be pre-pended onto the error
800 string, 'as_hash_footer' which will be appended, and 'as_hash_join'
801 which will be used to join the arrayref. The only argument required
802 to force the stringification is 'as_hash_join'.
804 # if this returns the following
805 my $hash = $err_obj->as_hash;
807 # {key1_error => ['error1', 'error2']}
809 # then this would return the following
810 my $hash = $err_obj->as_hash({
811 as_hash_suffix => '_foo',
812 as_hash_join => '<br />',
813 as_hash_header => '<span class="error">'
814 as_hash_footer => '</span>'
817 # {key1_foo => '<span class="error">error1<br />error2</span>'}
823 Any key in a validation hash matching the pattern
824 m/^group \s+ (\w+)$/x is considered a group option (the reason
825 that either group or general may be used is that CGI::Ex::Validate
826 used to have the concept of validation groups - these were not
827 commonly used so support has been removed as of the 2.10 release).
828 (the old name of 'general' vs 'group' is still supported but deprecated)
834 Used as a group section heading when as_array or as_string is called
837 'group title' => 'Title of errors',
841 Order in which to validate key/value pairs of group.
843 'group order' => [qw(user pass email OR phone)],
857 Alias for 'group order'.
861 If specified - the entire hashref will only be validated if
862 the "if" conditions are met.
864 'group validate_if => {field => 'email', required => 1},
866 This group would only validate all fields if the email field
871 If raise_error is true, any call to validate that fails validation
872 will die with an error object as the value.
874 =item C<no_extra_fields>
876 If no_extra_fields is true, validate will add errors for any field found
877 in form that does not have a field_val hashref in the validation hash.
878 Default is false. If no_extra_fields is set to 'used', it will check for
879 any keys that were not in a group that was validated.
881 An important exception to this is that field_val hashrefs or field names listed
882 in a validate_if or required_if statement will not be included. You must
883 have an explicit entry for each key.
887 These items allow for an override of the default errors.
889 'group required_error' => '$name is really required',
890 'group max_len_error' => '$name must be shorter than $value characters',
892 my $self = CGI::Ex::Validate->new({
893 max_len_error => '$name must be shorter than $value characters',
896 =item C<as_array_title>
898 Used as the section title for all errors that occur, when as_array
899 or as_string is called by the error object.
901 =item C<as_array_prefix>
903 Used as prefix to individual errors that occur, when as_array
904 or as_string is called by the error object. Each individual error
905 will be prefixed with this string. Headings will not be prefixed.
908 =item C<as_string_join>
910 When as_string is called, the values from as_array will be joined with
911 as_string_join. Default value is "\n".
913 =item C<as_string_header>
915 If set, will be pre-pended onto the string when as_string is called.
917 =item C<as_string_footer>
919 If set, will be pre-pended onto the string when as_string is called.
921 =item C<as_hash_suffix>
923 Added on to key names during the call to as_hash. Default is '_error'.
925 =item C<as_hash_join>
927 By default, as_hash will return hashref values that are errors joined with
928 the default as_hash_join value of <br />. It can also return values that are
929 arrayrefs of the errors. This can be done by setting as_hash_join to a non-true value
932 =item C<as_hash_header>
934 If as_hash_join has been set to a true value, as_hash_header may be set to
935 a string that will be pre-pended on to the error string.
937 =item C<as_hash_footer>
939 If as_hash_join has been set to a true value, as_hash_footer may be set to
940 a string that will be postpended on to the error string.
944 Defaults to {submit => 1}. This controls when the javascript validation
945 will take place. May be passed any or all or load, submit, change, or blur.
946 Multiple events may be passed in the hash.
948 'group onevent' => {submit => 1, change => 1}',
950 A comma separated string of types may also be passed:
952 'group onevent' => 'submit,change,blur,load',
954 Currently, change and blur will not work for dynamically matched
955 field names such as 'm/\w+/'. Support will be added.
959 Defaults document.validate_set_hook which defaults to nothing. If
960 "group set_hook" or document.validate_set_hook are set to a function,
961 they will be passed the key name of a form element that had a
962 validation error and the error that will be set. If a true value is
963 returned, then validate will not also the inline error. If no value
964 or false is returned (default) the validate will continue setting the
965 inline error. This gives full control over setting inline
966 errors. samples/validate_js_2_onchange.html has a good example of
969 'group set_hook' => "function (args) {
970 alert("Setting error to field "+args.key);
973 The args parameter includes key, value, val_hash, and form.
975 The document.validate_set_hook option is probably the better option to use,
976 as it helps to separate display functionality out into your html templates
977 rather than storing too much html logic in your CGI.
981 Similar to set_hook, but called when inline error is cleared. Its
982 corresponding default is document.validate_clear_hook. The clear hook
983 is also sampled in samples/validate_js_2_onchange.html
985 'group clear_hook' => "function (args) {
986 alert("Clear error on field "+args.key);
989 The args parameter includes key, val_hash, form, and was_valid.
993 If set to true, the javascript validation will not attempt to generate
994 inline errors when the only "group onevent" type is "submit". Default
995 is true. Inline errors are independent of confirm and alert errors.
997 'group no_inline' => 1,
1001 If set to true, the javascript validation will try to use an alert
1002 instead of a confirm to inform the user of errors when one of the
1003 "group onevent" types is "submit". Alert and confirm are independent
1004 or inline errors. Default is false.
1006 'group no_confirm' => 1,
1010 If set to true, the javascript validation will not show an alert box
1011 when errors occur. Default is false. This option only comes into
1012 play if no_confirm is also set. This option is only in effect if
1013 "group onevent" includes "submit". This option is independent of
1014 inline errors. Although it is possible to turn off all errors by
1015 setting no_inline, no_confirm, and no_alert all to 1, it is suggested
1016 that at least one of the error reporting facilities is left on.
1018 'group no_alert' => 1,
1024 CGI::Ex::Validate provides for having duplicate validation on the
1025 client side as on the server side. Errors can be shown in any
1026 combination of inline and confirm, inline and alert, inline only,
1027 confirm only, alert only, and none. These combinations are controlled
1028 by the group options no_inline, no_confirm, and no_alert.
1029 Javascript validation can be generated for a page using the
1030 C<-E<gt>generate_js> method of CGI::Ex::Validate.
1032 (Note: It is also possible to store the validation inline with the
1033 html as YAML and have it read in using the HTML conf handler - but
1034 this feature has been deprecated - see the included html samples for
1037 Generate JS will create something similar to the following (based on your validation):
1039 <script src="/cgi-bin/js/CGI/Ex/validate.js"></script>
1041 document.validation = {
1042 'group no_confirm': 1,
1043 'group no_alert': 1,
1044 'group onevent': 'change,blur,submit',
1045 'group order': ['username', 'password'],
1055 if (document.check_form) document.check_form('my_form_name');
1058 If inline errors are enabled (default), each error that occurs will attempt
1059 to find an html element with its name as the id. For example, if
1060 the field "username" failed validation and created a "username_error",
1061 the javascript would set the html of <span id="username_error"></span>
1062 to the error message.
1064 It is suggested to use something like the following so that you can
1065 have inline javascript validation as well as report validation errors
1066 from the server side as well.
1068 <span class=error id=password_error>[% password_error %]</span><br>
1070 If the javascript fails for some reason, the form should still be able
1071 to submit as normal (fail gracefully).
1073 Additionally, there are two hooks that are called when ever an inline
1074 error is set or cleared. The following hooks are used in
1075 samples/validate_js_2_onchange.html to highlight the row and set an icon.
1077 document.validate_set_hook = function (args) {
1078 document.getElementById(args.key+'_img').innerHTML
1079 = '<span style="font-weight:bold;color:red">!</span>';
1080 document.getElementById(args.key+'_row').style.background
1084 document.validate_clear_hook = function (args) {
1085 if (args.was_valid) {
1086 document.getElementById(args.key+'_img').innerHTML
1087 = '<span style="font-weight:bold;color:green">+</span>';
1088 document.getElementById(args.key+'_row').style.background
1091 document.getElementById(args.key+'_img').innerHTML = '';
1092 document.getElementById(args.key+'_row').style.background = '#fff';
1096 These hooks can also be set as "group clear_hook" and "group set_hook"
1097 which are defined further above.
1099 If the confirm option is used ("group onevent" includes submit and
1100 "group no_confirm" is false), the errors will be displayed to the
1101 user. If they choose OK they will be able to try and fix the errors.
1102 If they choose cancel, the form will submit anyway and will rely on
1103 the server to do the validation. This is for fail safety to make sure
1104 that if the javascript didn't validate correctly, the user can still
1109 Thanks to Eamon Daly for providing bug fixes for bugs in validate.js
1110 caused by HTML::Prototype.
1114 This module may be distributed under the same terms as Perl itself.
1118 Paul Seamons <paul at seamons dot com>